FD Full Manual
FD Full Manual
LAB MANUAL
Prepared By
Mr. Wasim Yasin
Assistant Professor
Department of CSD
K.S. Institute of Technology
K S INSTITUTE OF TECHNOLOGY
VISION
“To impart quality technical education with ethical values, employable
skills and research to achieve excellence”
MISSION
VISION
MISSION
PO2: Problem Analysis: Identify, Formulate, review research literature and analyze complex
engineering problems related to CSE and reaching substantiated conclusions using first principles
of mathematics, natural sciences and engineering sciences
PO5: Modern Tool Usage: Create, Select and apply appropriate techniques, resources and modern
engineering and IT tools including prediction and modeling to computer science related complex
engineering activities with an understanding of the limitations
PO6: The Engineer and Society: Apply Reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities relevant
to the CSE professional engineering practice
PO7: Environment and Sustainability: Understand the impact of the CSE professional
engineering solutions in societal and environmental contexts and demonstrate the knowledge of,
and need for sustainable development
PO8: Ethics: Apply Ethical Principles and commit to professional ethics and responsibilities and
norms of the engineering practice
PO9: Individual and Team Work: Function effectively as an individual and as a member or
leader in diverse teams and in multidisciplinary Settings
PO12: Life-Long Learning: Recognize the need for and have the preparation and ability to engage in
independent and life-long learning the broadest context of technological change
INDEX
1. Prescribed Syllabus 7
2. Installation of Python, Django and Visual Studio code editors can be demonstrated. 9
4. Develop a Django app that displays current date and time in server 11
5. Develop a Django app that displays date and time four hours ahead and four hours 12
before as an offset of current date and time in server.
6. Develop a simple Django app that displays an unordered list of fruits and ordered list 13
of selected students for an event
7. Develop a layout.html with a suitable header (containing navigation menu) and 15
footer with copyright and developer information. Inherit this layout.html and create
3 additional pages: contact us, About Us and Home page of any website.
8. Develop a Django app that performs student registration to a course. It should also 18
display list of students registered for any selected course. Create students and
course as models with enrolment as ManyToMany field.
For student and course models created in Lab experiment for Module2, register 21
9.
admin interfaces, perform migrations and illustrate data entry through admin forms.
10. Develop a Model form for student that contains his topic chosen for project, 23
languages used and duration with a model called project.
11. For students enrolment developed in Module 2, create a generic class view which 27
displays list of students and detailview that displays student details for any selected
student in the list.
Develop example Django app that performs CSV and PDF generation for any 30
12.
models created in previous laboratory component.
13. Develop a registration page for student enrolment as done in Module 2 but without 33
page refresh using AJAX.
14. Develop a search application in Django using AJAX that displays courses enrolled 36
by a student being searched.
15. VIVA VOCE Questions 39
Fullstack Development Laboratory (21CS62)
PROGRAM 1
Installation of Python, Django and Visual Studio code editors can be demonstrated.
In command prompt:
pip install Django
PROGRAM 2
Creation of virtual environment, Django project and App should be demonstrated
PROGRAM 3
Develop a Django app that displays current date and time in server
• Create a virtual environment: python -m venv myenv
• Activate the virtual environment: myenv\Scripts\activate
• django-admin startproject datetime_project
• cd datetime_project
• python manage.py startapp datetime_app
• Add the App to INSTALLED_APPS: datetime_project/settings.py and add datetime_app to the
INSTALLED_APPS
• In datetime_app/views.py:
• In datetime_app/templates/datetime_app/current_datetime.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Current Date and Time</title>
</head>
<body>
<h1>Current Date and Time</h1>
<p>{{ current_date }}</p>
</body>
</html>
• In datetime_app/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.current_datetime, name='current_datetime'),
]
• In datetime_project/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('datetime_app.urls')),
]
Run the Django command: python manage.py runserver
PROGRAM 4
Develop a Django app that displays date and time four hours ahead and four hours
before as an offset of current date and time in server.
Create a virtual environment
django-admin startproject datetime_project
cd datetime_project
python manage.py startapp datetime_app
datetime_project/settings.py
Add datetime_app to the INSTALLED_APPS list
In the datetime_app/views.py:
datetime_project/urls.py:
PROGRAM 5
Develop a simple Django app that displays an unordered list of fruits and ordered list
of selected students for an event
1. Create a virtual environment
2. django-admin startproject FruitStudentEvent
3. cd FruitStudentEvent
4. python manage.py startapp eventapp
Add eventapp to the INSTALLED_APPS list in FruitStudentEvent/settings.py
</head>
<body>
<h1>Unordered List of Fruits</h1>
<ul>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
</ul>
<h1>Ordered List of Students</h1>
<ol>
{% for student in students %}
<li>{{ student }}</li>
{% endfor %}
</ol>
</body>
</html>
PROGRAM 6
Develop a layout.html with a suitable header (containing navigation menu) and footer
with copyright and developer information. Inherit this layout.html and create 3
additional pages: contact us, About Us and Home page of any website.
Step 1: Setting Up Django Project and Application
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="{% url 'home' %}">Home</a></li>
<li><a href="{% url 'about' %}">About Us</a></li>
<li><a href="{% url 'contact' %}">Contact Us</a></li>
</ul>
</nav>
</header>
<main>
{% block content %}{% endblock %}
Department of CSD, KSIT Page 15
Fullstack Development Laboratory (21CS62)
</main>
</body>
</html>
home.html:
{% extends "layout.html" %}
{% block content %}
<h1>Welcome to My Website</h1>
<p>This is the home page of our website. We are glad to have you here!</p>
{% endblock %}
about.html:
{% extends "layout.html" %}
{% block content %}
<h1>About Us</h1>
<p>Learn more about our website and the team behind it.</p>
{% endblock %}
contact.html:
{% extends "layout.html" %}
{% block content %}
<h1>Contact Us</h1>
<p>If you have any questions, feel free to reach out to us!</p>
{% endblock %}
main/urls.py:
urlpatterns = [
path('', views.home, name='home'),
path('about/', views.about, name='about'),
path('contact/', views.contact, name='contact'),
]
Department of CSD, KSIT Page 16
Fullstack Development Laboratory (21CS62)
Edit mywebsite/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls')),
]
def home(request):
return render(request, 'home.html')
def about(request):
return render(request, 'about.html')
def contact(request):
return render(request, 'contact.html')
PROGRAM 7
Develop a Django app that performs student registration to a course. It should also
display list of students registered for any selected course. Create students and course
as models with enrolment as ManyToMany field.
2. Define Models
# registration/models.py
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(unique=True)
def __str__(self):
return self.name
class Course(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.name
class Enrolment(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
class Meta:
unique_together = ('student', 'course')
def __str__(self):
return f'{self.student.name} enrolled in {self.course.name}'
admin.py
# registration/admin.py
from django.contrib import admin
from .models import Student, Course, Enrolment
admin.site.register(Student)
admin.site.register(Course)
admin.site.register(Enrolment)
Department of CSD, KSIT Page 18
Fullstack Development Laboratory (21CS62)
# registration/views.py
from django.shortcuts import render, redirect
from .models import Course, Student, Enrolment
def course_list(request):
courses = Course.objects.all()
return render(request, 'registration/course_list.html', {'courses': courses})
6. Create Templates
registration/templates/registration/course_list.html
registration/templates/registration/register_student.html
<!-- register_student.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Register Student</title>
</head>
<body>
<h1>Register for {{ course.name }}</h1>
<form method="post">
{% csrf_token %}
Department of CSD, KSIT Page 19
Fullstack Development Laboratory (21CS62)
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Register</button>
</form>
</body>
</html>
registration/templates/registration/course_detail.html
7. Define URLs
urls.py
# registration/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.course_list, name='course_list'),
path('course/<int:course_id>/', views.register_student, name='register_student'),
path('course/<int:course_id>/detail/', views.course_detail, name='course_detail'),
]
# course_registration/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('registration/', include('registration.urls')),
]
PROGRAM 8
For student and course models created in Lab experiment for Module2, register admin
interfaces, perform migrations and illustrate data entry through admin forms.
1. Register Models in Django Admin
# registration/admin.py
from django.contrib import admin
from .models import Student, Course, Enrolment
@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
list_display = ('name', 'email')
@admin.register(Course)
class CourseAdmin(admin.ModelAdmin):
list_display = ('name', 'description')
@admin.register(Enrolment)
class EnrolmentAdmin(admin.ModelAdmin):
list_display = ('student', 'course')
2. Perform Migrations
Add Students:
o Click on "Students" under the Registration section.
o Click "Add Student" and enter student details (name and email).
Add Courses:
o Click on "Courses" under the Registration section.
o Click "Add Course" and enter course details (name and description).
Enrol Students to Courses:
o You can manage enrolments indirectly by adding students to courses.
o Navigate to a course detail page, click "Add another Enrolment", and select the student
from the dropdown.
Illustrative Example
Let's illustrate adding a sample student and course through the Django admin interface:
1. Add a Student:
o Go to http://127.0.0.1:8000/admin/registration/student/add/
o Fill in the form:
Name: John Doe
Email: john.doe@example.com
o Click "Save".
2. Add a Course:
o Go to http://127.0.0.1:8000/admin/registration/course/add/
o Fill in the form:
Name: Introduction to Django
Description: A beginner-friendly course on Django web framework.
o Click "Save".
3. Enrol the Student to the Course:
o Navigate back to the list of Courses
(http://127.0.0.1:8000/admin/registration/course/ ).
o Click on "Introduction to Django".
o Under "Enrolments", click "Add another Enrolment".
o Select "John Doe" from the list of available students.
o Click "Save".
Viewing Enrolments
PROGRAM 9
Develop a Model form for student that contains his topic chosen for project,
languages used and duration with a model called project.
1. Define Models
class Project(models.Model):
topic = models.CharField(max_length=200)
languages_used = models.CharField(max_length=100)
duration = models.CharField(max_length=50)
def __str__(self):
return self.topic
class Student(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(unique=True)
def __str__(self):
return self.name
2. Create ModelForm
Create a ModelForm for the Student model that includes fields for the project details.
forms.py
Create a new file forms.py in your registration app directory if it doesn't exist, and define the
StudentForm using Django's ModelForm.
Department of CSD, KSIT Page 23
Fullstack Development Laboratory (21CS62)
# registration/forms.py
class StudentForm(forms.ModelForm):
class Meta:
model = Student
If you need to create or update views to handle this form, modify your views accordingly. Below is a
basic example to illustrate handling the form.
views.py
def student_form(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()
else:
form = StudentForm()
4. Create Templates
Create a template (student_form.html) to render the form. Ensure you handle the project field
appropriately, possibly providing choices or allowing free text entry.
student_form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
</body>
</html>
If you want to manage Student and Project data through Django admin, register them in admin.py as
shown earlier in our previous example.
6. Run Migrations
After defining the models and forms, make sure to run migrations to apply these changes to your
database:
This setup creates a Student model with a foreign key relationship to a Project model, allowing students to
choose a project topic, specify languages used, and project duration. The StudentForm allows you to create or
Department of CSD, KSIT Page 25
Fullstack Development Laboratory (21CS62)
update student records with associated project details via a user-friendly form interface. Adjust the form and
views according to your specific requirements, such as adding validation, customizing field widgets, or handling
form submission logic as needed.
PROGRAM 10
For students enrolment developed in Module 2, create a generic class view which
displays list of students and detailview that displays student details for any selected
student in the list.
Create a Django project:
django-admin startproject student_course_project
cd student_course_project
Add the app to the project's settings: Edit student_course_project/settings.py and add 'registration' to the
INSTALLED_APPS list:
INSTALLED_APPS = [
...
'registration',
]
class Student(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(unique=True)
def __str__(self):
return f"{self.first_name} {self.last_name}"
class Course(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
students = models.ManyToManyField(Student, related_name='courses')
def __str__(self):
return self.name
class StudentListView(ListView):
model = Student
template_name = 'registration/student_list.html'
context_object_name = 'students'
class StudentDetailView(DetailView):
Department of CSD, KSIT Page 27
Fullstack Development Laboratory (21CS62)
model = Student
template_name = 'registration/student_detail.html'
context_object_name = 'student'
1. Configure URLs: Create a new file registration/urls.py and add the following code:
urlpatterns = [
path('students/', StudentListView.as_view(), name='student_list'),
path('students/<int:pk>/', StudentDetailView.as_view(), name='student_detail'),
]
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('registration.urls')),
]
student_list.html:
<!DOCTYPE html>
<html>
<head>
<title>Student List</title>
</head>
<body>
<h1>Students</h1>
<ul>
{% for student in students %}
<li><a href="{% url 'student_detail' student.pk %}">{{ student.first_name }} {{ student.last_name
}}</a></li>
{% endfor %}
</ul>
</body>
</html>
student_detail.html:
<!DOCTYPE html>
<html>
<head>
<title>Student Details</title>
</head>
<body>
<h1>{{ student.first_name }} {{ student.last_name }}</h1>
Run the following commands to make migrations and migrate the database:
Admin interface: Edit registration/admin.py to register the models with the admin site:
admin.site.register(Student)
admin.site.register(Course)
Student Registration Form (optional): If you want to add a form to register students to courses, create a form in
registration/forms.py:
class StudentRegistrationForm(forms.ModelForm):
class Meta:
model = Student
fields = ['first_name', 'last_name', 'email', 'courses']
widgets = {
'courses': forms.CheckboxSelectMultiple(),
}
Add a view and URL for the registration form, and create a template for it.
PROGRAM 11
Develop example Django app that performs CSV and PDF generation for any models
created in previous laboratory component.
1. django-admin startproject student_project
2. cd student_project
3. python manage.py startapp projects
4. student_project/settings.py
INSTALLED_APPS = [
...
'projects',
]
5. projects/models.py:
from django.db import models
class Project(models.Model):
student_name = models.CharField(max_length=100)
topic = models.CharField(max_length=200)
languages_used = models.CharField(max_length=200)
duration = models.CharField(max_length=50)
def __str__(self):
return self.topic
In CMD:
6. python manage.py makemigrations
7. python manage.py migrate
8. projects/forms.py:
from django import forms
from .models import Project
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ['student_name', 'topic', 'languages_used', 'duration']
9. projects/views.py
from django.shortcuts import render, redirect
from .forms import ProjectForm
from .models import Project
import csv
from django.http import HttpResponse
from reportlab.pdfgen import canvas
def project_create_view(request):
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
form.save()
return redirect('project_list')
Department of CSD, KSIT Page 30
Fullstack Development Laboratory (21CS62)
else:
form = ProjectForm()
return render(request, 'projects/project_form.html', {'form': form})
def project_list_view(request):
projects = Project.objects.all()
return render(request, 'projects/project_list.html', {'projects': projects})
def export_projects_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="projects.csv"'
writer = csv.writer(response)
writer.writerow(['Student Name', 'Topic', 'Languages Used', 'Duration'])
projects = Project.objects.all()
for project in projects:
writer.writerow([project.student_name, project.topic, project.languages_used, project.duration])
return response
def export_projects_pdf(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="projects.pdf"'
p = canvas.Canvas(response)
p.drawString(100, 800, "Project List")
projects = Project.objects.all()
y = 750
for project in projects:
p.drawString(100, y, f"Student Name: {project.student_name}")
p.drawString(100, y-15, f"Topic: {project.topic}")
p.drawString(100, y-30, f"Languages Used: {project.languages_used}")
p.drawString(100, y-45, f"Duration: {project.duration}")
y -= 60
p.showPage()
p.save()
return response
10. projects/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('new/', views.project_create_view, name='project_create'),
path('', views.project_list_view, name='project_list'),
path('export/csv/', views.export_projects_csv, name='export_projects_csv'),
path('export/pdf/', views.export_projects_pdf, name='export_projects_pdf'),
]
11. student_project/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('projects/', include('projects.urls')),
]
12. projects/templates/projects
project_form.html:
project_list.html:
http://127.0.0.1:8000/projects/
PROGRAM 12
Develop a registration page for student enrolment as done in Module 2 but without
page refresh using AJAX.
1. django-admin startproject student_enrollment
2. cd student_enrollment
3. python manage.py startapp projects
4. student_enrollment/settings.py
INSTALLED_APPS = [
...
'projects',
]
5. projects/models.py:
class Student(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField(unique=True)
phone = models.CharField(max_length=15)
def __str__(self):
return f"{self.first_name} {self.last_name}"
In CMD:
8. projects/forms.py:
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['first_name', 'last_name', 'email', 'phone']
9. projects/views.py
from django.shortcuts import render
from django.http import JsonResponse
from .forms import StudentForm
def student_registration_view(request):
form = StudentForm()
return render(request, 'projects/student_registration.html', {'form': form})
def student_registration_ajax(request):
if request.method == 'POST':
form = StudentForm(request.POST)
Department of CSD, KSIT Page 33
Fullstack Development Laboratory (21CS62)
if form.is_valid():
form.save()
return JsonResponse({'status': 'success'})
else:
return JsonResponse({'status': 'error', 'errors': form.errors})
return JsonResponse({'status': 'invalid request'})
10. projects/urls.py:
urlpatterns = [
path('register/', views.student_registration_view, name='student_registration'),
path('register/ajax/', views.student_registration_ajax, name='student_registration_ajax'),
]
11. student_enrollment/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('projects/', include('projects.urls')),
]
12. projects/templates/projects
student_registration.html:
In CMD:
http://127.0.0.1:8000/projects/register/
PROGRAM 13
Develop a search application in Django using AJAX that displays courses enrolled by a
student being searched.
1. django-admin startproject school
2. cd school
3. django-admin startapp courses
4. school/settings.py
INSTALLED_APPS = [
...
'courses',
]
5. courses/models.py
class Course(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Student(models.Model):
name = models.CharField(max_length=100)
courses = models.ManyToManyField(Course)
def __str__(self):
return self.name
6. courses/admin.py:
admin.site.register(Student)
admin.site.register(Course)
8. courses/serializers.py
from rest_framework import serializers
from .models import Student
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ['id', 'name', 'courses']
depth = 1
9. courses/views.py
def index(request):
return render(request, 'courses/index.html')
@api_view(['GET'])
def student_courses(request):
student_name = request.GET.get('student_name', None)
if student_name:
try:
student = Student.objects.get(name=student_name)
serializer = StudentSerializer(student)
return Response(serializer.data)
except Student.DoesNotExist:
return Response({'error': 'Student not found'}, status=404)
return Response({'error': 'No student name provided'}, status=400)
10. courses/urls.py
urlpatterns = [
path('', views.index, name='index'),
path('api/student_courses/', views.student_courses, name='student_courses'),
]
11. school/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('courses.urls')),
]
12. courses/templates/courses/index.html:
<!DOCTYPE html>
<html>
<head>
<title>Search Courses</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#search').click(function(){
var student_name = $('#student_name').val();
$.ajax({
url: 'api/student_courses/',
data: {
Department of CSD, KSIT Page 37
Fullstack Development Laboratory (21CS62)
'student_name': student_name
},
success: function(data) {
$('#results').html('');
if(data.error) {
$('#results').html(data.error);
} else {
var courses = data.courses.map(course => course.name).join(', ');
$('#results').html('Courses: ' + courses);
}
}
});
});
});
</script>
</head>
<body>
<h1>Search Courses by Student Name</h1>
<input type="text" id="student_name" placeholder="Enter student name">
<button id="search">Search</button>
<div id="results"></div>
</body>
</html>
In CMD:
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
VIVA-VOCE Questions
Basic Concepts
1. What is Django?
o Django is a high-level Python web framework that encourages rapid development and clean,
pragmatic design.
2. How do you create a new Django project?
o django-admin startproject projectname
3. How do you create a new Django app?
o python manage.py startapp appname
4. What is the purpose of the settings.py file?
o It contains all the configuration settings for the Django project, such as database configuration,
installed apps, middleware, templates, etc.
5. How do you run a Django development server?
o python manage.py runserver
6. What is a Django model?
o A Django model is a Python class that defines the structure of database tables. Each attribute of
the model represents a database field.
7. How do you create a model in Django?
o Define a class in the models.py file of your app and inherit from django.db.models.Model.
8. What are Django migrations?
o Migrations are Django’s way of propagating changes made to models (adding a field, deleting a
model, etc.) into the database schema.
9. How do you apply migrations in Django?
o python manage.py makemigrations and python manage.py migrate
10. What is a Django view?
o A view function is a Python function that takes a web request and returns a web response. Views
are used to process the user’s requests and return the appropriate response.
Intermediate Concepts
Advanced Concepts
Front-end Integration
Security
o Use third-party packages like Pillow for image processing and optimize images before serving
them.
99. How do you use gunicorn and nginx for performance?
o Use Gunicorn as the application server and Nginx as the reverse proxy to handle static files and
distribute load.
100. How do you use database indexing in Django? - Define indexes on model fields using
the index_together and unique_together options in the model’s Meta class.
************End**********