[go: up one dir, main page]

0% found this document useful (0 votes)
78 views44 pages

FD Full Manual

Uploaded by

mshreyas817
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views44 pages

FD Full Manual

Uploaded by

mshreyas817
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

K S INSTITUTE OF TECHNOLOGY

#14 Raghuvanahalli Kanakapura road Bangalore – 560109

Department of Computer Science and Design

LAB MANUAL

“FULLSTACK DEVELOPMENT LABORATORY”


Subject code: 21CS62

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

 To attract and retain highly qualified, experienced & committed faculty.

 To create relevant infrastructure

 Network with industry & premier institutions to encourage emergence

of new ideas by providing research & development facilities to strive

for academic excellence

 To inculcate the professional & ethical values among young students


with employable skills & knowledge acquired to transform the
society
DEPARTMENT OF COMPUTER SCIENCE AND DESIGN

VISION

To prepare exceptionally skilled and outstanding professionals in


Computer Science & Design with research skills and ethics for
addressing societal needs.

MISSION

1) Instill a commitment to enhancing design, and development skills by


Encouraging
2) To create awareness of research and ethics among students to excel in
various facets of the design profession.
3) To groom the students with the needed practical skills to cater to the
needs of society through projects.
PROGRAM OUTCOMES (PO’s)

PO1: Engineering Knowledge: Apply knowledge of mathematics and science, with


fundamentals of Computer Science & Engineering to be able to solve complex engineering
problems related to CSE.

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

PO3: Design/Development of solutions: Design solutions for complex engineering problems


related to CSE and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety and the cultural societal and
environmental considerations

PO4: Conduct Investigations of Complex problems: Use research–based knowledge and


research methods including design of experiments, analysis and interpretation of data, and synthesis
of the information to provide valid conclusions.

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

PO10: Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large such as able to comprehend and with write
effective reports and design documentation, make effective presentations and give and receive clear
instructions.
PO11: Project Management and Finance: Demonstrate knowledge and understanding of the
engineering management principles and apply these to one’s own work, as a member and leader in a
team, to manage projects and in multi-disciplinary environments

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

SL Experiment Name/ Description Page


No. No.

1. Prescribed Syllabus 7

2. Installation of Python, Django and Visual Studio code editors can be demonstrated. 9

3. Creation of virtual environment, Django project and App should be demonstrated 10

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)

VI Semester Fullstack Development Lab Syllabus

FULLSTACK DEVELOPMENT LABORATORY


Course Code 21CS62 CIE Marks 50
Teaching Hours/Week (L: T:P: 0:0:2:0 SEE Marks 50
S)
Total Hours of Pedagogy 20 Total Marks 100
Credits 1 Exam Hours 03
Course Learning Objectives:
CLO 1. Explain the use of learning full stack web development.
CLO 2. Make use of rapid application development in the design of responsive web pages.
CLO 3. Illustrate Models, Views and Templates with their connectivity in Django for full stack web development.
CLO 4. Demonstrate the use of state management and admin interfaces automation in Django.
CLO 5. Design and implement Django apps containing dynamic pages with SQL databases.

Sl. No. Practice Programs


1. Installation of Python, Django and Visual Studio code editors can be demonstrated.
2. Creation of virtual environment, Django project and App should be demonstrated
3. Develop a Django app that displays current date and time in server
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.
5. Develop a simple Django app that displays an unordered list of fruits and ordered list of
selected students for an event
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.
Develop a Django app that performs student registration to a course. It should also display list
7.
of students registered for any selected course. Create students and course as models with
enrolment as ManyToMany field.
8. For student and course models created in Lab experiment for Module2, register admin
interfaces, perform migrations and illustrate data entry through admin forms.
Develop a Model form for student that contains his topic chosen for project, languages used
9.
and duration with a model called project.
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.
11. Develop example Django app that performs CSV and PDF generation for any models created in
previous laboratory component.
12. Develop a registration page for student enrolment as done in Module 2 but without page
refresh using AJAX.
13 Develop a search application in Django using AJAX that displays courses enrolled by a student
being searched.

Department of CSD, KSIT Page 7


Fullstack Development Laboratory (21CS62)
Course outcome (Course Skill Set)
At the end of the course the student will be able to:
CO 1. Understand the working of MVT based full stack web development with Django.
CO 2. Designing of Models and Forms for rapid development of web pages.
CO 3. Analyze the role of Template Inheritance and Generic views for developing full stack web
applications.
CO 4. Apply the Django framework libraries to render nonHTML contents like CSV and PDF.
CO 5. Perform jQuery based AJAX integration to Django Apps to build responsive full stack web
applications

Department of CSD, KSIT Page 8


Fullstack Development Laboratory (21CS62)

PROGRAM 1
Installation of Python, Django and Visual Studio code editors can be demonstrated.

The steps of installation:

Ensure Python is installed: https://www.python.org/downloads/ (python - - version)

In command prompt:
pip install Django

Install Visual Studio like below:

Department of CSD, KSIT Page 9


Fullstack Development Laboratory (21CS62)

PROGRAM 2
Creation of virtual environment, Django project and App should be demonstrated

1. Create a virtual environment: python -m venv myenv


2. Activate the virtual environment: myenv\Scripts\activate
3. Install Django: pip install django
4. Verify the installation: django-admin --version
5. To create a new Django project: django-admin startproject
6. To create Django apps within the project: python manage.py startapp

Department of CSD, KSIT Page 10


Fullstack Development Laboratory (21CS62)

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:

from django.shortcuts import render


from datetime import datetime
def current_datetime(request):
now = datetime.now()
return render(request, 'datetime_app/current_datetime.html', {'current_date': now})

• 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

Department of CSD, KSIT Page 11


Fullstack Development Laboratory (21CS62)

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:

from django.shortcuts import render


from django.http import HttpResponse
from django.utils.timezone import now # Use timezone-aware datetime
from datetime import timedelta
def time_with_offsets(request):
current_time = now()
time_four_hours_ahead = current_time + timedelta(hours=4)
time_four_hours_before = current_time - timedelta(hours=4)
html = f"""
<html>
<body>
<p>Current date and time: {current_time}</p>
<p>Date and time four hours ahead: {time_four_hours_ahead}</p>
<p>Date and time four hours before: {time_four_hours_before}</p>
</body>
</html>
"""
return HttpResponse(html)

datetime_project/urls.py:

from django.contrib import admin


from django.urls import path
from datetime_app.views import time_with_offsets
urlpatterns = [
path('admin/', admin.site.urls),
path('', time_with_offsets, name='time_with_offsets'),
]

Department of CSD, KSIT Page 12


Fullstack Development Laboratory (21CS62)

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

Create the View in eventapp/views.py:


from django.shortcuts import render
def display_lists(request):
fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]
students = ["John Doe", "Jane Smith", "Alice Johnson", "Bob Brown"]
context = {
'fruits': fruits,
'students': students
}
return render(request, 'eventapp/lists.html', context)

In eventapp/urls.py, create a URL pattern for the view:


from django.urls import path
from .views import display_lists
urlpatterns = [
path(‘ ‘, display_lists, name='display_lists'),
]

In FruitStudentEvent/urls.py, include the URLs from eventapp:


from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('eventapp.urls')),
]

Create the Template Directory:


Create a directory templates inside the eventapp directory, and then create a subdirectory eventapp inside it:
mkdir -p eventapp/templates/eventapp

Create the Template File:


Create a file named lists.html inside eventapp/templates/eventapp/:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fruits and Students</title>
Department of CSD, KSIT Page 13
Fullstack Development Laboratory (21CS62)

</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>

• python manage.py migrate


• python manage.py runserver

Department of CSD, KSIT Page 14


Fullstack Development Laboratory (21CS62)

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

1. Create a Django Project:


django-admin startproject mywebsite
cd mywebsite

2. Create a Django Application:


python manage.py startapp main

3. Add the Application to INSTALLED_APPS:


Edit mywebsite/settings.py and add 'main' to INSTALLED_APPS:
INSTALLED_APPS = [
...
'main',
]

Step 2: Create the Templates Directory


1. Create a templates directory inside the main app:
mkdir -p main/templates

Inside main/templates, create three HTML files:

Step 3: Create layout.html

Create layout.html in main/templates:

<!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>

Step 4: Create home.html, about.html, and contact.html

home.html:

{% extends "layout.html" %}

{% block title %}Home - My Website{% endblock %}

{% 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 title %}About Us - My Website{% endblock %}

{% 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 title %}Contact Us - My Website{% endblock %}

{% block content %}
<h1>Contact Us</h1>
<p>If you have any questions, feel free to reach out to us!</p>
{% endblock %}

Step 5: Configure URLs:

1. Create a urls.py in the main app:

main/urls.py:

from django.urls import path


from . import views

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)

2. Include the main app's URLs in the project's urls.py

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')),
]

Step 6: Create Views


Create the corresponding views in main/views.py:

from django.shortcuts import render

def home(request):
return render(request, 'home.html')

def about(request):
return render(request, 'about.html')

def contact(request):
return render(request, 'contact.html')

Step 8: Run the Server


python manage.py runserver

Department of CSD, KSIT Page 17


Fullstack Development Laboratory (21CS62)

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.

1. Set Up Your Django Project and App


django-admin startproject course_registration
cd course_registration
python manage.py startapp registration

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}'

3. Create and Apply Migrations

python manage.py makemigrations


python manage.py migrate

4. Create Admin Interface (Optional)

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)

5. Create Views and Templates

# 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})

def register_student(request, course_id):


course = Course.objects.get(pk=course_id)
if request.method == 'POST':
student_email = request.POST.get('email')
student, created = Student.objects.get_or_create(email=student_email)
enrolment, created = Enrolment.objects.get_or_create(student=student, course=course)
return redirect('course_detail', course_id=course.id)
return render(request, 'registration/register_student.html', {'course': course})

def course_detail(request, course_id):


course = Course.objects.get(pk=course_id)
students = course.student_set.all()
return render(request, 'registration/course_detail.html', {'course': course, 'students': students})

6. Create Templates

registration/templates/registration/course_list.html

<!-- course_list.html -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Course List</title>
</head>
<body>
<h1>Available Courses</h1>
<ul>
{% for course in courses %}
<li><a href="{% url 'register_student' course.id %}">{{ course.name }}</a></li>
{% endfor %}
</ul>
</body>
</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

<!-- course_detail.html -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Course Detail</title>
</head>
<body>
<h1>{{ course.name }} - Registered Students</h1>
<ul>
{% for student in students %}
<li>{{ student.name }} - {{ student.email }}</li>
{% empty %}
<li>No students registered yet.</li>
{% endfor %}
</ul>
</body>
</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'),
]

8. Include App URLs in Project URLs


course_registration/urls.py

# 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')),
]

Department of CSD, KSIT Page 20


Fullstack Development Laboratory (21CS62)

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

python manage.py makemigrations


python manage.py migrate

3. Access Django Admin Interface

python manage.py runserver

4. Add Data Using Admin Interface

 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

Department of CSD, KSIT Page 21


Fullstack Development Laboratory (21CS62)

 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

To view enrolled students for a course:

 Click on the course name (Introduction to Django) in the admin interface.


 You'll see the enrolled student listed under the "Enrolments" section.

Department of CSD, KSIT Page 22


Fullstack Development Laboratory (21CS62)

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

First, define the Student and Project models in your registration/models.py.

from django.db import 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)

project = models.ForeignKey(Project, on_delete=models.SET_NULL, null=True, blank=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

from django import forms

from .models import Student

class StudentForm(forms.ModelForm):

class Meta:

model = Student

fields = ['name', 'email', 'project']

3. Update Views (Optional)

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

from django.shortcuts import render, redirect

from .forms import StudentForm

def student_form(request):

if request.method == 'POST':

form = StudentForm(request.POST)

if form.is_valid():

form.save()

return redirect('student_list') # Replace with appropriate redirect

else:

form = StudentForm()

return render(request, 'registration/student_form.html', {'form': form})

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.

Department of CSD, KSIT Page 24


Fullstack Development Laboratory (21CS62)

student_form.html

<!-- registration/templates/registration/student_form.html -->

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Student Project Form</title>

</head>

<body>

<h1>Student Project Form</h1>

<form method="post">

{% csrf_token %}

{{ form.as_p }}

<button type="submit">Submit</button>

</form>

</body>

</html>

5. Register Models in Admin (Optional)

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:

python manage.py makemigrations

python manage.py migrate

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.

Department of CSD, KSIT Page 26


Fullstack Development Laboratory (21CS62)

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

Create a Django app:


python manage.py startapp registration

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',
]

Step 2: Define the models

Edit registration/models.py to define the Student and Course models:

from django.db import models

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

Step 3: Create views

Edit registration/views.py to create the views:

from django.views.generic import ListView, DetailView


from .models import Student, Course

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'

Step 4: Set up URLs and templates

1. Configure URLs: Create a new file registration/urls.py and add the following code:

from django.urls import path


from .views import StudentListView, StudentDetailView

urlpatterns = [
path('students/', StudentListView.as_view(), name='student_list'),
path('students/<int:pk>/', StudentDetailView.as_view(), name='student_detail'),
]

Edit student_course_project/urls.py to include the app's URLs:

from django.contrib import admin


from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('registration.urls')),
]

Create templates: Create templates in registration/templates/registration/:

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>

Department of CSD, KSIT Page 28


Fullstack Development Laboratory (21CS62)
<p>Email: {{ student.email }}</p>
<h2>Courses</h2>
<ul>
{% for course in student.courses.all %}
<li>{{ course.name }}</li>
{% endfor %}
</ul>
</body>
</html>

Step 5: Migrate the database

Run the following commands to make migrations and migrate the database:

python manage.py makemigrations


python manage.py migrate

Additional Steps for Admin Interface and Registration Form

Admin interface: Edit registration/admin.py to register the models with the admin site:

from django.contrib import admin


from .models import Student, Course

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:

from django import forms


from .models import Student, Course

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.

Department of CSD, KSIT Page 29


Fullstack Development Laboratory (21CS62)

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

Department of CSD, KSIT Page 31


Fullstack Development Laboratory (21CS62)

urlpatterns = [
path('admin/', admin.site.urls),
path('projects/', include('projects.urls')),
]

12. projects/templates/projects
project_form.html:

<!-- projects/templates/projects/project_form.html -->


<h2>New Project</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>

project_list.html:

<!-- projects/templates/projects/project_list.html -->


<h2>Project List</h2>
<table>
<tr>
<th>Student Name</th>
<th>Topic</th>
<th>Languages Used</th>
<th>Duration</th>
</tr>
{% for project in projects %}
<tr>
<td>{{ project.student_name }}</td>
<td>{{ project.topic }}</td>
<td>{{ project.languages_used }}</td>
<td>{{ project.duration }}</td>
</tr>
{% endfor %}
</table>
<a href="{% url 'export_projects_csv' %}">Export CSV</a>
<a href="{% url 'export_projects_pdf' %}">Export PDF</a>

13. python manage.py runserver

http://127.0.0.1:8000/projects/

Department of CSD, KSIT Page 32


Fullstack Development Laboratory (21CS62)

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:

from django.db import models

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:

6. python manage.py makemigrations


7. python manage.py migrate

8. projects/forms.py:

from django import forms


from .models import Student

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:

from django.urls import path


from . import views

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

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

student_registration.html:

<!-- projects/templates/projects/student_registration.html -->


<!DOCTYPE html>
<html>
<head>
<title>Student Registration</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$('#student-form').on('submit', function(event){
event.preventDefault();
$.ajax({
url: '{% url "student_registration_ajax" %}',
method: 'POST',
data: $(this).serialize(),
success: function(response){
if (response.status == 'success') {
$('#message').html('<p>Student registered successfully!</p>');
$('#student-form')[0].reset();
} else if (response.status == 'error') {
$('#message').html('<p>Error: ' + JSON.stringify(response.errors) + '</p>');
}
}
});
});
Department of CSD, KSIT Page 34
Fullstack Development Laboratory (21CS62)
});
</script>
</head>
<body>
<h2>Student Registration</h2>
<div id="message"></div>
<form id="student-form" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
</body>
</html>

In CMD:

python manage.py runserver

http://127.0.0.1:8000/projects/register/

Department of CSD, KSIT Page 35


Fullstack Development Laboratory (21CS62)

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

from django.db import models

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:

from django.contrib import admin


from .models import Student, Course

admin.site.register(Student)
admin.site.register(Course)

7. Install Django REST framework:


pip install djangorestframework

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

Department of CSD, KSIT Page 36


Fullstack Development Laboratory (21CS62)
from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Student
from .serializers import StudentSerializer

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

from django.urls import path


from . import views

urlpatterns = [
path('', views.index, name='index'),
path('api/student_courses/', views.student_courses, name='student_courses'),
]

11. school/urls.py

from django.contrib import admin


from django.urls import include, path

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

Department of CSD, KSIT Page 38


Fullstack Development Laboratory (21CS62)

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

11. What is the purpose of the urls.py file?


o It contains URL patterns (mappings) that route URLs to the appropriate view functions.
12. How do you include an app’s URLs in the project’s URL configuration?
o Use include() function in the project's urls.py file.
13. What is a Django template?
o A Django template is a text file that defines the structure or layout of a file (like an HTML file),
and it allows Django to dynamically generate HTML content.
14. How do you render a template in a Django view?
o Use render(request, 'template_name.html', context) .
15. What is the purpose of Django’s admin interface?
o The Django admin interface is a built-in interface for managing application data. It allows you to
add, edit, and delete data models.
16. How do you register a model with the Django admin?
o Add the model to the admin.py file using admin.site.register(ModelName).
17. What are Django forms?
o Django forms are used to handle user input, validate data, and display forms in templates.
18. How do you create a form in Django?
o Define a class that inherits from forms.Form or forms.ModelForm in the forms.py file of
your app.
19. What is a Django QuerySet?
o A QuerySet is a collection of database queries that can be executed, filtered, and manipulated.
Department of CSD, KSIT Page 39
Fullstack Development Laboratory (21CS62)

20. How do you filter QuerySets in Django?


o Use the filter() method on a model manager, e.g.,
Model.objects.filter(field=value).

Advanced Concepts

21. What are Django signals?


o Signals are a way to allow decoupled applications to get notified when certain events occur.
22. How do you connect a signal to a receiver function?
o Use the @receiver decorator or signal.connect(receiver, sender).
23. What is middleware in Django?
o Middleware is a way to process requests globally before they reach the view or after the view has
processed them.
24. How do you create custom middleware?
o Define a class with __init__(), __call__(), and optionally process_view(),
process_exception(), or process_template_response() methods.
25. What are Django generic views?
o Generic views are a set of built-in views that handle common tasks like displaying a list of
objects, handling form submissions, etc.
26. How do you use a generic view in Django?
o Import the desired generic view class and configure it in the urls.py file.
27. What is Django REST framework (DRF)?
o DRF is a powerful and flexible toolkit for building Web APIs with Django.
28. How do you serialize data in Django REST framework?
o Define a serializer class that inherits from serializers.ModelSerializer or
serializers.Serializer.
29. What is a Django context processor?
o Context processors are functions that provide context data to templates across all views.
30. How do you add a custom context processor?
o Define a function in a Python file and add its path to the
TEMPLATES['OPTIONS']['context_processors'] setting.

Database and Models

31. What are the different types of fields in Django models?


o Common field types include CharField, TextField, IntegerField, BooleanField,
DateField, DateTimeField, ForeignKey, ManyToManyField, and OneToOneField.
32. How do you define a one-to-many relationship in Django?
o Use ForeignKey in the model definition.
33. How do you define a many-to-many relationship in Django?
o Use ManyToManyField in the model definition.
34. How do you define a one-to-one relationship in Django?
o Use OneToOneField in the model definition.
35. What is the purpose of the Meta class in Django models?
o The Meta class is used to define metadata options for the model, such as ordering, permissions,
unique constraints, etc.
36. How do you enforce unique constraints on a model field?
o Set the unique=True parameter in the field definition.
37. How do you create a custom model manager in Django?
o Define a class that inherits from models.Manager and add custom methods.
38. How do you perform raw SQL queries in Django?
o Use the raw() method on the model manager.
39. How do you add custom validation to a Django model?
o Override the clean() method or use the validators parameter on the field definition.

Department of CSD, KSIT Page 40


Fullstack Development Laboratory (21CS62)

40. How do you create a model method in Django?


o Define a method within the model class.

Authentication and Authorization

41. How do you handle user authentication in Django?


o Use the built-in authentication system with django.contrib.auth.
42. How do you create a custom user model in Django?
o Define a model that inherits from AbstractBaseUser and PermissionsMixin, and configure
the AUTH_USER_MODEL setting.
43. How do you create login and logout views in Django?
o Use django.contrib.auth.views.LoginView and LogoutView.
44. How do you restrict access to a view to authenticated users?
o Use the @login_required decorator.
45. How do you handle user registration in Django?
o Create a form for user registration, handle form submission in a view, and create a new user in the
view.
46. How do you reset a user's password in Django?
o Use the built-in password reset views: PasswordResetView, PasswordResetConfirmView,
etc.
47. How do you create user permissions in Django?
o Define permissions in the model’s Meta class and use the user.has_perm() method to check
permissions.
48. How do you create user groups in Django?
o Use the Group model from django.contrib.auth.models to create and manage groups.
49. How do you use the @permission_required decorator in Django?
o Use @permission_required('app_label.permission_name') on the view.
50. How do you create custom authentication backends in Django?
o Define a class that inherits from BaseBackend and implement the authenticate() and
get_user() methods.

Front-end Integration

51. How do you serve static files in Django?


o Configure the STATIC_URL and STATICFILES_DIRS settings and use the {% static
'path/to/file' %} template tag.
52. How do you serve media files in Django?
o Configure the MEDIA_URL and MEDIA_ROOT settings and use the {% get_media_prefix %}
template tag.
53. How do you include CSS and JavaScript files in a Django template?
o Use the {% load static %} tag and {% static 'path/to/file' %} within the <link>
or <script> tags.
54. How do you use Django template inheritance?
o Create a base template with {% block block_name %}{% endblock %} tags and extend it in
other templates using {% extends 'base.html' %}.
55. How do you pass data from a view to a template?
o Pass a context dictionary to the render() function in the view.
56. How do you handle AJAX requests in Django?
o Use JavaScript to send AJAX requests and handle them in Django views, returning JSON
responses using JsonResponse.
57. How do you use Django forms with AJAX?
o Use JavaScript to submit the form via AJAX and handle form validation and response in the
Django view.
58. How do you use Django with a front-end framework like React or Angular?
Department of CSD, KSIT Page 41
Fullstack Development Laboratory (21CS62)
o Serve the front-end application as static files and use Django as the backend API, often through
Django REST framework.
59. How do you handle CORS in Django when using a separate front-end application?
o Use the django-cors-headers package to handle Cross-Origin Resource Sharing.
60. How do you deploy a Django application with a front-end framework?
o Build the front-end application, place the build files in the Django static files directory, and
configure the web server to serve the static files.

Testing and Debugging

61. How do you write unit tests in Django?


o Create test cases in a tests.py file using the unittest module or django.test.TestCase.
62. How do you run tests in Django?
o Use the python manage.py test command.
63. How do you write integration tests in Django?
o Use the django.test.Client to simulate HTTP requests and test the interaction between
different parts of the application.
64. What is the purpose of the assertContains method in Django tests?
o It checks if a response contains a specific value.
65. How do you use the django-debug-toolbar?
o Install the package, add it to the INSTALLED_APPS and MIDDLEWARE, and configure the
DEBUG_TOOLBAR_PANELS setting.
66. How do you enable Django’s debug mode?
o Set the DEBUG setting to True.
67. What is the purpose of Django’s assertRedirects method in tests?
o It checks if a response is a redirect to a specific URL.
68. How do you test Django forms?
o Create test cases to validate form input, checking for valid and invalid data.
69. How do you use the @override_settings decorator in Django tests?
o Temporarily override settings for a specific test case.
70. How do you debug a Django application?
o Use the built-in Python debugger (pdb), logging, and the django-debug-toolbar for
debugging.

Deployment and Scaling

71. How do you deploy a Django application?


o Use a web server like Gunicorn or uWSGI to serve the application, and a web server like Nginx
or Apache to handle static files and reverse proxy.
72. How do you configure Gunicorn for a Django application?
o Install Gunicorn, and run the application using the gunicorn myproject.wsgi command.
73. How do you use environment variables in Django settings?
o Use the os.environ module to read environment variables and set them in the settings.py
file.
74. How do you handle static files in production?
o Collect static files using the collectstatic management command and serve them using a
web server.
75. What is the purpose of the ALLOWED_HOSTS setting in Django?
o It specifies a list of hosts/domain names that the Django site can serve.
76. How do you use django-environ?
o Use the django-environ package to manage environment variables and settings.
77. How do you configure Django for different environments (development, production)?
o Create separate settings files for each environment and use environment variables to switch
between them.
78. How do you use Docker to containerize a Django application?
Department of CSD, KSIT Page 42
Fullstack Development Laboratory (21CS62)

o Create a Dockerfile and docker-compose.yml file to define the application environment


and dependencies.
79. How do you scale a Django application?
o Use load balancing, database replication, caching, and horizontal scaling techniques.
80. How do you use Celery with Django?
o Install Celery, configure a message broker (e.g., RabbitMQ or Redis), and create task functions to
handle background processing.

Security

81. How do you prevent SQL injection in Django?


o Use Django’s ORM to create and execute database queries, which automatically escape inputs.
82. How do you prevent Cross-Site Scripting (XSS) in Django?
o Use Django’s template system, which automatically escapes variables, and the bleach library to
sanitize user input.
83. How do you prevent Cross-Site Request Forgery (CSRF) in Django?
o Use Django’s built-in CSRF protection middleware and the {% csrf_token %} template tag.
84. How do you handle sensitive data in Django settings?
o Use environment variables and secrets management tools to keep sensitive data out of version
control.
85. What is the purpose of the SECURE_SSL_REDIRECT setting in Django?
o It forces all HTTP connections to be redirected to HTTPS.
86. How do you implement HTTPS in Django?
o Obtain an SSL certificate and configure your web server to use it.
87. How do you use Django’s is_safe_url function?
o Use it to validate that a URL is safe to redirect to, preventing open redirect vulnerabilities.
88. What are Django’s security middleware classes?
o SecurityMiddleware, XFrameOptionsMiddleware, and
ContentSecurityPolicyMiddleware.
89. How do you configure Django for secure cookie handling?
o Use settings like SESSION_COOKIE_SECURE, CSRF_COOKIE_SECURE,
SESSION_COOKIE_HTTPONLY, and CSRF_COOKIE_HTTPONLY.
90. How do you use Django’s allowed_hosts middleware?
o Ensure that only requests from allowed hosts are processed, preventing host header attacks.

Optimization and Performance

91. How do you use Django’s caching framework?


o Configure a cache backend in the settings and use cache decorators and APIs to cache views,
querysets, and data.
92. How do you optimize database queries in Django?
o Use select_related() and prefetch_related() to reduce the number of database queries.
93. How do you use Django’s Paginator class?
o Use Paginator to divide querysets into pages and display them in views and templates.
94. How do you profile a Django application?
o Use profiling tools like django-silk, cProfile, and the django-debug-toolbar.
95. How do you use Django’s Memcached backend?
o Install and configure python-memcached or pylibmc and set it as the cache backend in the
settings.
96. How do you use Django’s signals for performance monitoring?
o Connect signals to custom monitoring functions to track performance metrics.
97. How do you use django-compressor?
o Install and configure django-compressor to compress CSS and JavaScript files.
98. How do you optimize image handling in Django?

Department of CSD, KSIT Page 43


Fullstack Development Laboratory (21CS62)

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**********

Department of CSD, KSIT Page 44

You might also like