FSD Manual
FSD Manual
FSD Manual
LABORATORY MANUAL
SEMESTER : VI
SUBCODE : 21CS62
NAME :
USN :
SECTION:
Program Outcomes
POs Description
Engineering knowledge: Apply the knowledge of mathematics, science, engineering
PO1 fundamentals, and computer science and business systems to the solution of
complex engineering and societal problems.
Problem analysis: Identify, formulate, review research literature, and analyze
PO2 complex engineering and business problems reaching substantiated conclusions
using first principles of mathematics, natural sciences, and engineering sciences
Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needs
PO3
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based knowledge and
PO4 research methods including design of experiments, analysis and interpretation of
data, and synthesis of the information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and
PO5 modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations
The engineer and society: Apply reasoning informed by the contextual knowledge
PO6 to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering and business practices
Environment and sustainability: Understand the impact of the professional
PO7 engineering solutions in business societal and environmental contexts, and
demonstrate the knowledge of, and need for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and
PO8
responsibilities and norms of the engineering and business practices.
Individual and team work: Function effectively as an individual, and as a member
PO9
or leader in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with
the engineering community and with society at large, such as, being able to
PO10
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions
Project management and finance: Demonstrate knowledge and understanding of the
engineering, business and management principles and apply these to one’s own
PO11
work, as a member and leader in a team, to manage projects and in multidisciplinary
environments.
Life-long learning: Recognize the need for, and have the preparation and ability to
PO12 engage in independent and life-long learning in the broadest context of
technological change.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
VISION
The East Point College of Engineering and Technology aspires to be a globally
acclaimed institution, recognized for excellence in engineering education, applied
research and nurturing students for holistic development.
MISSION
M1: To create Engineering graduates through quality education and to nurture innovation,
creativity and excellence in teaching, learning and research
M2: To serve the technical, scientific, economic and societal developmental needs of our
communities.
M3: To induce integrity, teamwork, critical thinking, personality development and ethics in
students and to lay the foundation for lifelong learning
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
VISION
MISSION
M2: To augment experiential learning skills to serve technical, scientific, economic, and
social developmental needs.
M3: To instill integrity, critical thinking, personality development, and ethics in students for a
successful career in Industries, Research, and Entrepreneurship.
PROGRAM EDUCATIONAL OBJECTIVES (PEOs)
PEO 1:To produce graduates who can perform technical roles to contribute effectively in
software industries and R&D Centre.
PEO 2:To produce graduates having the ability to adapt and contribute in key domains of
computer science and engineering to develop competent solutions.
PEO 3:To produce graduates who can provide socially and ethically responsible solutions
while adapting to new trends in the domain to carve a successful career in the industry
PSO1: To conceptualize, model, design, simulate, analyze, develop, test, and validate
computing systems and solve technical problems arising in the field of computer science &
engineering.
PSO2: To specialize in the sub-areas of computer science & engineering systems such as
cloud computing, Robotic Process Automation, cyber security, big data analytics, user
interface design, and IOT to meet industry requirements.
PSO3: To build innovative solutions to meet the demands of the industry using appropriate
tools and techniques.
COURSE LEARNING OBJECTIVES
COURSE OUTCOMES
CO 1. Understand the working of MVT based full stack web development with Django.
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 non HTML contents like CSV and PDF.
CO 5. Perform jQuery based AJAX integration to Django Apps to build responsive full stack
web applications.
FSD LAB 21CS62
Prerequisite
Students should be familiarized about Python installation and setting Python environment
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
Laboratory Component-2
1. Develop a simple Django app that displays an unordered list of fruits and ordered list of selected
students for an event.
2. 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
2 and Home page of any website.
3. 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.
Laboratory Component-3
1. For student and course models created in Lab experiment for Module2, register admin interfaces,
3 perform migrations and illustrate data entry through admin forms.
2. Develop a Model form for student that contains his topic chosen for project, languages used and
duration with a model called project.
Laboratory Component-4
4 1. For students enrolment developed in Module 2, create a generic class view which displays list of students and
detail view that displays student details for any selected student in the list.
2. Develop example Django app that performs CSV and PDF generation for any models created in previous
laboratory component.
Laboratory Component-5
5 1. Develop a registration page for student enrolment as done in Module 2 but without page refresh using AJAX.
2. Develop a search application in Django using AJAX that displays courses enrolled by a student being searched.
DEPT.OFCSE,EPCET Page 7
FSD LAB 21CS62
Laboratory Component - 1:
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.
1.1 Installation
a) Python:
1. Download the latest Python installer from https://www.python.org/downloads/. (Python 3.11.5
preferred).
2. Run the installer and follow the on-screen instructions. Ensure "Add Python to PATH" is checked for
easy access from the command line.
3. Open a command prompt or terminal and type python --version to verify installation.
# Linux
sudo apt-get install python3-venv # If needed
python3 -m venv myenv
source myenv/bin/activate
# macOS
python3 -m venv myenv
source myenv/bin/activate
# Windows
py -3 -m venv myenv
myenv\scripts\activate
3. Open the project folder in VS Code by running code, or by running VS Code and using the File > Open
Folder command.
4. In VS Code, open the Command Palette (View > Command Palette or (Ctrl+Shift+P)). Then select the
Python: Select Interpreter command:
DEPT.OFCSE,EPCET Page 9
FSD LAB 21CS62
5. The command presents a list of available interpreters that VS Code can locate automatically (your list
will vary; if you don't see the desired interpreter, see Configuring Python environments). From the list,
select the virtual environment in your project folder that starts with myenv:
6. Run Terminal: Create New Terminal (Ctrl+Shift+`) from the Command Palette, which creates a terminal
and automatically activates the virtual environment by running its activation script.
DEPT.OFCSE,EPCET Page 10
FSD LAB 21CS62
Note: On Windows, if your default terminal type is PowerShell, you may see an error that it cannot run
activate.ps1 because running scripts is disabled on the system. The error provides a link for information on
how to allow scripts. Otherwise, use Terminal: Select Default Profile to set "Command Prompt" or "Git
Bash" as your default instead.
7. Update pip in the virtual environment by running the following command in the VS Code Terminal:
8. Install Django in the virtual environment by running the following command in the VS Code Terminal:
You now have a self-contained environment ready for writing Django code. VS Code activates the
environment automatically when you use Terminal: Create New Terminal (Ctrl+Shift+`). If you open a
separate command prompt or terminal, activate the environment by running source myenv/bin/activate
(Linux/macOS) or myenv\Scripts\Activate.ps1 (Windows). You know the environment is activated when the
command prompt shows (myenv) at the beginning.
DEPT.OFCSE,EPCET Page 11
FSD LAB 21CS62
In Django terminology, a "Django project" is composed of several site-level configuration files, along with
one or more "apps" that you deploy to a web host to create a full web application. A Django project can
contain multiple apps, each of which typically has an independent function in the project, and the same app
can be in multiple Django projects. An app, for its part, is just a Python package that follows certain
conventions that Django expects.
To create a minimal Django app, then, it's necessary to first create the Django project to serve as the
container for the app, then create the app itself. For both purposes, you use the Django administrative
utility, django-admin, which is installed when you install the Django package.
o manage.py: The Django command-line administrative utility for the project. You run
administrative commands for the project using python manage.py <command> [options].
o A subfolder named myproject, which contains the following files:
__init__.py: an empty file that tells Python that this folder is a Python package.
asgi.py: an entry point for ASGI-compatible web servers to serve your project. You typically
leave this file as-is as it provides the hooks for production web servers.
settings.py: contains settings for Django project, which you modify in the course of developing
a web app.
urls.py: contains a table of contents for the Django project, which you also modify in the
course of development.
wsgi.py: an entry point for WSGI-compatible web servers to serve your project. You typically
leave this file as-is as it provides the hooks for production web servers.
When you run the server the first time, it creates a default SQLite database in the file db.sqlite3 that is
intended for development purposes, but can be used in production for low-volume web apps.
To verify the Django project, make sure your virtual environment is activated, then start Django's
development server using the command python manage.py runserver. The server runs on the default port
8000, and you see output like the following output in the terminal window:
DEPT.OFCSE,EPCET Page 12
FSD LAB 21CS62
Django's built-in web server is intended only for local development purposes. When you deploy to a web
host, however, Django uses the host's web server instead. The wsgi.py and asgi.py modules in the Django
project take care of hooking into the production servers.
If you want to use a different port than the default 8000, specify the port number on the command line,
such as python manage.py runserver 5000 .
3. Ctrl+click the http://127.0.0.1:8000/ URL in the terminal output window to open your default
browser to that address. If Django is installed correctly and the project is valid, you see the default
page shown below. The VS Code terminal output window also shows the server log.
4. When you're done, close the browser window and stop the server in VS Code using Ctrl+C as indicated
in the terminal output window.
DEPT.OFCSE,EPCET Page 13
FSD LAB 21CS62
The command creates a folder called myapp that contains a number of code files and one subfolder. Of
these, you frequently work with views.py (that contains the functions that define pages in your web app)
and models.py (that contains classes defining your data objects). The migrations folder is used by Django's
administrative utility to manage database versions as discussed later in this tutorial. There are also the files
apps.py (app configuration), admin.py (for creating an administrative interface), and tests.py (for creating
tests), which are not covered here.
def date_time_offset(request):
# Get the current date and time on the server
current_datetime = datetime.now()
# Calculate the date and time four hours ahead and four hours before
datetime_ahead = current_datetime + timedelta(hours=4)
datetime_before = current_datetime - timedelta(hours=4)
DEPT.OFCSE,EPCET Page 14
FSD LAB 21CS62
4.Create a file, myapp/urls.py, with the contents below. The urls.py file is where you specify patterns to
route different URLs to their appropriate views.
#urls.py (myapp/urls.py)
5. The myproject folder also contains a urls.py file, which is where URL routing is actually handled.
Open myproject/urls.py and modify it to match the following code (you can retain the instructive
comments if you like). This code pulls in the app's myapp/urls.py using django.urls.include, which
keeps the app's routes contained within the app. This separation is helpful when a project contains
multiple apps.
#urls.py (myproject/urls.py)
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("", include("myapp.urls")),
path("admin/", admin.site.urls),
]
6. In the myproject/settings.py file, locate the INSTALLED_APPS list and add the following entry,
which makes sure the project knows about the app so it can handle templating:
‘myapp’.
7. Inside the myapp folder, create a folder named templates, and then another subfolder named
myapp to match the app name (this two-tiered folder structure is typical Django convention).
In the templates/myapp folder, create a file named current_datetime.html with the contents below.
#current_datetime.html (myapp/templates/myapp/current_datetime.html)
DEPT.OFCSE,EPCET Page 15
FSD LAB 21CS62
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Current Time</title>
</head>
<body>
<h1>Current Time</h1>
<p>UTC Time: {{ utc_time }}</p>
<p>Indian Standard Time (IST): {{ ist_time }}</p>
</body>
</html>
In the templates/myapp folder, create a file named date_time_offset.html with the contents below.
9. In the VS Code Terminal, again with the virtual environment activated, run the development
server with python manage.py runserver and open a browser to http://127.0.0.1:8000/
10.In the url box of the browse, navigate to http://127.0.0.1:8000/current_datetime to view the current
date time. Similarly, navigate to http://127.0.0.1:8000/date_time_offset to view the offset time.
DEPT.OFCSE,EPCET Page 16
FSD LAB 21CS62
DEPT.OFCSE,EPCET Page 17
FSD LAB 21CS62
Laboratory Component - 2:
1. Develop a simple Django app that displays an unordered list of fruits and ordered list of
selected students for an event.
2. 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.
3. 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. In the VS Code Terminal with your virtual environment activated, run the administrative utility's
startapp command in your myproject folder (where manage.py resides):
#views.py
from django.shortcuts import render
def fruits_and_students(request):
print(request.build_absolute_uri())
fruits = ['Apple', 'Banana', 'Orange', 'Grapes']
students = ['Alice', 'Bob', 'Charlie', 'David']
return render(request, 'fruits_and_students/fruits_and_students.html', {'fruits': fruits,
'students': students})
3. Create a file, fruits_and_students/urls.py, with the contents below. The urls.py file is where you specify
patterns to route different URLs to their appropriate views.
#urls.py (fruits_and_students/urls.py)
from django.urls import path
from .views import fruits_and_students
urlpatterns = [
path('', fruits_and_students, name='fruits_and_students'),
]
4. The myproject folder also contains a urls.py file, which is where URL routing is actually handled. Keep
in mind the myproject/urls.py will be used to handle all of the laboratory component apps’ that will be
built. Just add the path url routing line of code to the urlpatterns list every time in the already existing
code.
DEPT.OFCSE,EPCET Page 18
FSD LAB 21CS62
#urls.py (myproject/urls.py)
urlpatterns = [
path("", include("myapp.urls")),
path("admin/", admin.site.urls),
path('fruits_and_students/', include('fruits_and_students.urls')),
]
5. In the myproject/settings.py file, locate the INSTALLED_APPS list and add the following entry, which
makes sure the project knows about the app so it can handle templating:
‘fruits_and_students’.
6. Inside the fruits_and_students folder, create a folder named templates, and then another subfolder named
fruits_and_students to match the app name (this two-tiered folder structure is typical Django convention).
#fruits_and_students.html (fruits_and_students/templates/fruits_and_students/
fruits_and_students.html)
<!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>
</head>
<body>
<h1>Fruits</h1>
<ul>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
</ul>
<h1>Selected Students</h1>
<ol>
{% for student in students %}
<li>{{ student }}</li>
{% endfor %}
</ol>
</body>
</html>
8. In the VS Code Terminal, again with the virtual environment activated, run the development
server with python manage.py runserver and open a browser to http://127.0.0.1:8000/
DEPT.OFCSE,EPCET Page 19
FSD LAB 21CS62
1. In the VS Code Terminal with your virtual environment activated, run the administrative utility's
startapp command in your myproject folder (where manage.py resides):
#views.py
from django.shortcuts import render
def home(request):
return render(request, 'website_pages/home.html')
def about_us(request):
return render(request, 'website_pages/about_us.html')
def contact_us(request):
return render(request, 'website_pages/contact_us.html')
DEPT.OFCSE,EPCET Page 20
FSD LAB 21CS62
3. Create a file, website_pages/urls.py, with the contents below. The urls.py file is where you specify
patterns to route different URLs to their appropriate views.
urlpatterns = [
path('home/', views.home, name='home'),
path('about_us/', views.about_us, name='about_us'),
path('contact_us/', views.contact_us, name='contact_us'),
]
4. The myproject folder also contains a urls.py file, which is where URL routing is actually handled.
#urls.py (myproject/urls.py)
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("", include("myapp.urls")),
path("admin/", admin.site.urls),
path('fruits_and_students/', include('fruits_and_students.urls')),
path('', include('website_pages.urls')),
]
5. In the myproject/settings.py file, locate the INSTALLED_APPS list and add the following entry,
which makes sure the project knows about the app so it can handle templating:
‘website_pages’.
6. Inside the website_pages folder, create a folder named templates. Inside the templates folder,
create a file named layout.html.
#templates/layout.html (The CSS is optional)
<!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>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
header {
background-color: #333;
color: #fff;
padding: 10px;
}
DEPT.OFCSE,EPCET Page 21
FSD LAB 21CS62
nav ul {
list-style-type: none;
padding: 0;
}
nav ul li {
display: inline;
margin-right: 20px;
}
nav ul li a {
text-decoration: none;
color: #fff;
}
main {
padding: 20px;
}
footer {
background-color: #333;
color: #fff;
text-align: center;
padding: 10px;
position: fixed;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="{% url 'home' %}">Home</a></li>
<li><a href="{% url 'about_us' %}">About Us</a></li>
<li><a href="{% url 'contact_us' %}">Contact Us</a></li>
</ul>
</nav>
</header>
<main>
{% block content %}
{% endblock %}
</main>
<footer>
<p>© 2024 My Website. All rights reserved. </p>
<p>Developed by EPCET</p>
</footer>
</body>
</html>
DEPT.OFCSE,EPCET Page 22
FSD LAB 21CS62
7. Inside the templates folder, create another subfolder named website_pages to match the app name (this
two-tiered folder structure is typical Django convention).
In the templates/website_pages folder, create files named home.html, about_us.html, and contact_us.html
with the contents below.
#home.html (website_pages/templates/website_pages/home.html)
{% extends 'layout.html' %}
{% block title %}Home{% endblock %}
{% block content %}
<h1>Welcome to East Point College of Engineering and Technology <h1>
<p>Empowering students with a blend of knowledge and innovation. </p>
<p>Nestled in the bustling city of Bengaluru, our campus is a hub of academic excellence and
cutting-edge research.</p>
<h2>Discover Your Potential</h2>
<ul>
<li><strong>Undergraduate Programs:</strong> Dive into our diverse range of engineering
courses designed to fuel your passion and drive innovation.</li>
<li><strong>Postgraduate Programs:</strong> Advance your expertise with our
specialized master's programs and embrace leadership in technology.</li>
</ul>
<p>Join our vibrant community where ideas flourish and inventions come to life in our state-of-
the-art labs and research centers.</p>
<p>Benefit from our strong industry ties and placement programs that open doors to exciting
career opportunities.</p>
{% endblock %}
#about_us.html (website_pages/templates/website_pages/about_us.html)
{% extends 'layout.html' %}
{% block title %}About Us{% endblock %}
{% block content %}
<h1>Our Legacy</h1>
<p>Founded on the principles of quality education and societal contribution, we've been at the
forefront of technological education for over four decades.</p>
<h1>Vision and Mission</h1>
<p>Our vision is to be a beacon of knowledge that lights the way for aspiring minds, and our
mission is to nurture innovative thinkers who will shape the future of technology.</p>
<h1>Campus Life</h1>
<p>Experience a dynamic campus life enriched with cultural activities, technical clubs, and
community service initiatives that foster holistic development.</p>
{% endblock %}
#contact_us.html (website_pages/templates/website_pages/contact_us.html)
{% extends 'layout.html' %}
{% block title %}Contact Us{% endblock %}
{% block content %}
<h1>Get in Touch</h1>
<p>For admissions and inquiries, reach out to us at:</p>
<ul>
<li><strong>Email:</strong> [email protected]</li>
<li><strong>Phone:</strong> +91- 72042 29999</li>
</ul>
DEPT.OFCSE,EPCET Page 23
FSD LAB 21CS62
9. In the VS Code Terminal, again with the virtual environment activated, run the development server with
python manage.py runserver and open a browser to http://127.0.0.1:8000/
10.In the url box of the browse, navigate to http://127.0.0.1:8000/home to view the output. Similarly, you
can navigate through by clicking on the navigation menu. Also check out http://127.0.0.1:8000/about_us
and http://127.0.0.1:8000/contact_us
DEPT.OFCSE,EPCET Page 24
FSD LAB 21CS62
DEPT.OFCSE,EPCET Page 25
FSD LAB 21CS62
1. In the VS Code Terminal with your virtual environment activated, run the administrative utility's
startapp command in your myproject folder (where manage.py resides):
#views.py
from .forms import StudentForm, CourseForm
from .models import Student, Course
from django.shortcuts import render, redirect, get_object_or_404
def add_student(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()
# Redirect to a view that lists all students
return redirect('student_list')
else:
form = StudentForm()
return render(request, 'course_registration/add_student.html', {'form':
form})
def add_course(request):
if request.method == 'POST':
form = CourseForm(request.POST)
if form.is_valid():
form.save()
return redirect('course_registration')
else:
form = CourseForm()
return render(request, 'course_registration/add_course.html', {'form': form})
def register_student(request):
if request.method == 'POST':
student_name = request.POST.get('student_name')
course_id = request.POST.get('course_id')
# Validate that both student_name and course_id are provided
if not student_name or not course_id:
return render(request, 'course_registration/register_student.html', {'courses':
Course.objects.all(), 'error_message': 'Please provide both student name and select a course.'})
try:
# Retrieve the course based on course_id or return 404 if not found
course = get_object_or_404(Course, pk=course_id)
# Check if the student already exists in the database
student = Student.objects.filter(name=student_name).first()
DEPT.OFCSE,EPCET Page 26
FSD LAB 21CS62
if not student:
# If the student does not exist, return an error message
return render(request, 'course_registration/register_student.html', {'courses':
Course.objects.all(), 'error_message': 'Student does not exist in the database.'})
# Add the student to the course
course.students.add(student)
return redirect('course_registration')
except Course.DoesNotExist:
return render(request, 'course_registration/register_student.html', {'courses': Course.objects.all(),
'error_message': 'Invalid course ID. Please select a valid course.'})
# If not a POST request, render the registration form with all courses
return render(request, 'course_registration/register_student.html', {'courses': Course.objects.all()})
def course_registration(request):
courses = Course.objects.all()
return render(request, 'course_registration/course_registration.html', {'courses': courses})
3. Create a file, course_registration/urls.py, with the contents below. The urls.py file is where you specify
patterns to route different URLs to their appropriate views.
#urls.py (course_registration/urls.py)
from django.urls import path
from . import views
urlpatterns = [
path('add_student/', views.add_student, name='add_student'),
path('add_course/', views.add_course, name='add_course'),
path('register/', views.register_student, name='register_student'),
path('courses/', views.course_registration, name='course_registration'),
path('students_list/<int:course_id>/',
views.students_list, name='students_list'),
]
4. The myproject folder also contains a urls.py file, which is where URL routing is actually handled.
#urls.py (myproject/urls.py)
urlpatterns = [
path("", include("myapp.urls")),
path("admin/", admin.site.urls),
DEPT.OFCSE,EPCET Page 27
FSD LAB 21CS62
path('fruits_and_students/', include('fruits_and_students.urls')),
path('', include('website_pages.urls')),
path('registration/', include('course_registration.urls')),
]
class Course(models.Model):
name = models.CharField(max_length=100,unique=True)
students = models.ManyToManyField(Student, related_name='courses')
course_id = models.IntegerField(default=0,unique=True)
def __str__(self):
return self.name
class CourseForm(forms.ModelForm):
class Meta:
model = Course
fields = ['name', 'course_id']
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['name', 'date_of_birth', 'email']
7. In the myproject/settings.py file, locate the INSTALLED_APPS list and add the following entry, which
makes sure the project knows about the app so it can handle templating:
‘course_registration’
8. Create a templates folder, create inside templates folder, a subfolder named course_registration to match
the app name (this two-tiered folder structure is typical Django convention).
In the templates/course_registration folder, create files named add_student.html, add_course.html,
register_student.html, course_registration.html, and students_list.html with the contents below.
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Student</title>
</head>
<body>
<h1>Add Student</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
</body>
</html>
button[type="submit"] {
background-color: #007bff;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}
button[type="submit"]:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<h1>Add Course</h1>
<form method="POST">
{% csrf_token %}
<label for="course_name">Course Name:</label>
<input type="text" id="course_name" name="name" required>
<label for="course_id">Course ID:</label>
<input type="number" id="course_id" name="course_id" required>
<button type="submit">Add Course</button>
</form>
</body>
</html>
DEPT.OFCSE,EPCET Page 30
FSD LAB 21CS62
.form-control {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
box-sizing: border-box;
}
.btn {
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
}
.btn-primary {
background-color: #007bff;
}
</style>
</head>
<body>
<div class="container">
<h1>Register Student to Course</h1>
<form method="POST" class="form">
{% csrf_token %}
<div class="form-group">
<label for="student_name">Student Name:</label>
<input type="text" id="student_name" name="student_name" class="form-control"
required>
</div>
<div class="form-group">
<label for="course_id">Select Course:</label>
<select name="course_id" id="course_id" class="form-control">
{% for course in courses %}
<option value="{{ course.id }}">{{ course.name }}</option>
{% endfor %}
</select>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</body>
</html>
DEPT.OFCSE,EPCET Page 31
FSD LAB 21CS62
<style>
body {
font-family: Arial, sans-serif;
background-color: #f8f9fa;
margin: 0;
padding: 0;
}
.container {
max-width: 600px;
margin: 50px auto;
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.list-group {
list-style-type: none;
padding: 0;
}
.list-group-item {
margin-bottom: 10px;
}
.list-group-item a {
text-decoration: none;
color: #333;
}
</style>
</head>
<body>
<div class="container">
<h1>Course Registration</h1>
<ul class="list-group">
{% for course in courses %}
<li class="list-group-item">
<a href="{% url 'students_list' course.course_id %}">{{ course.name }} (ID: {{
course.course_id }})</a>
</li>
{% endfor %}
</ul>
</div>
</body>
</html>
DEPT.OFCSE,EPCET Page 32
FSD LAB 21CS62
body {
font-family: Arial, sans-serif;
background-color: #f8f9fa;
margin: 0;
padding: 0;
}
.container {
max-width: 600px;
margin: 50px auto;
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.list-group {
list-style-type: none;
padding: 0;
}
.list-group-item {
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="container">
<h1>Students Registered for {{ course.name }}</h1>
<ul class="list-group">
{% for student in students %}
<li class="list-group-item">{{ student.name }}</li>
{% empty %}
<li class="list-group-item">No students registered for this course.</li>
{% endfor %}
</ul>
</div>
</body>
</html>
10.In the VS Code Terminal, again with the virtual environment activated, run the below commands to
migrate changes.
python manage.py makemigrations
python manage.py migrate
11.In order to view the database and its tables, you can use SQLite DB Browser.
https://sqlitebrowser.org/dl/
12.In the VS Code Terminal, again with the virtual environment activated, run the development server with
python manage.py runserver and open a browser to http://127.0.0.1:8000/
DEPT.OFCSE,EPCET Page 33
FSD LAB 21CS62
13.In the url box of the browse, navigate to http://127.0.0.1:8000/registration/add_student to add the
students. Similarly, check out http://127.0.0.1:8000/registration/add_course to add courses,
http://127.0.0.1:8000/registration/register, http://127.0.0.1:8000/registration/courses, and
http://127.0.0.1:8000/registration/students_list/<course_id>
DEPT.OFCSE,EPCET Page 34
FSD LAB 21CS62
DEPT.OFCSE,EPCET Page 35
FSD LAB 21CS62
ManyToMany field application can be checked through the fact that multiple students can be enrolled to
multiple courses.
Try it out!!!!
Use the SQLite DB Browser to view, insert, update, and delete the records in the tables created in the
db.sqlite3 database.
1. Open SQLite DB Browser.
2. Click on Open Database.
DEPT.OFCSE,EPCET Page 36
FSD LAB 21CS62
DEPT.OFCSE,EPCET Page 37
FSD LAB 21CS62
Laboratory Component - 3:
1. For student and course models created in Lab experiment for Module2, register admin
interfaces, perform migrations and illustrate data entry through admin forms.
2. Develop a Model form for student that contains his topic chosen for project, languages used and duration
with a model called project.
3. Now to enter data through admin interfaces, we need to first create a super user to get access to the
admin dashboard. In the VS Code terminal run the below command,
4.Once the superuser is successfully created. Run the server in the VS Code terminal.
DEPT.OFCSE,EPCET Page 38
FSD LAB 21CS62
DEPT.OFCSE,EPCET Page 39
FSD LAB 21CS62
#views.py
from .models import Project
from .forms import ProjectForm
def project_list(request):
projects = Project.objects.all()
return render(request, 'course_registration/project_list.html', {'projects': projects})
def add_project(request):
if request.method == 'POST':
DEPT.OFCSE,EPCET Page 40
FSD LAB 21CS62
form = ProjectForm(request.POST)
if form.is_valid():
form.save()
return redirect('project_list')
else:
form = ProjectForm()
return render(request, 'course_registration/add_project.html', {'form': form})
2.In the course_registration/urls.py, include the new paths to existing urlpatterns list.
#urls.py (course_registration/urls.py)
… (to indicate rest of code)
path('project_list/', views.project_list, name='project_list'),
path('add_project/', views.add_project, name='add_project'),
…
3. Add below lines of code to existing course_registration/models.py
#models.py
…
class Project(models.Model):
topic = models.CharField(max_length=100)
languages_used = models.CharField(max_length=100)
duration = models.CharField(max_length=50)
def __str__(self):
return self.topic
…
5.In the templates/course_registration folder, create files named add_project.html, and project_list.html
with the contents below.
#templates/course_registration/add_project.html (The CSS is optional)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Project</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
}
DEPT.OFCSE,EPCET Page 41
FSD LAB 21CS62
h1 {
color: #333;
}
form {
background-color: #f9f9f9;
padding: 20px;
border-radius: 5px;
}
label {
display: block;
margin-bottom: 5px;
}
input[type="text"] {
width: 100%;
padding: 8px;
margin-bottom: 10px;
border-radius: 5px;
border: 1px solid #ccc;
}
button {
background-color: #007bff;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Add Project</h1>
<form method="post">
{% csrf_token %}
<label for="id_topic">Topic:</label>
{{ form.topic }}
<label for="id_languages_used">Languages used:</label>
{{ form.languages_used }}
<label for="id_duration">Duration:</label>
{{ form.duration }}
<button type="submit">Submit</button>
</form>
</body>
</html>
#templates/course_registration/project_list.html (The CSS is optional)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Project List</title>
<style>
DEPT.OFCSE,EPCET Page 42
FSD LAB 21CS62
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
}
h1 {
color: #333;
}
ul {
list-style-type: none;
padding: 0;
}
li {
margin-bottom: 10px;
background-color: #f9f9f9;
padding: 10px;
border-radius: 5px;
}
a{
text-decoration: none;
color: #007bff;
}
</style>
</head>
<body>
<h1>Project List</h1>
<ul>
{% for project in projects %}
<li>
<strong>{{ project.topic }}</strong><br>
<em>Languages used:</em> {{ project.languages_used }}<br>
<em>Duration:</em> {{ project.duration }}
</li>
{% empty %}
<li>No projects available</li>
{% endfor %}
</ul>
<a href="{% url 'add_project' %}">Add Project</a>
</body>
</html>
DEPT.OFCSE,EPCET Page 43
FSD LAB 21CS62
8. In the VS Code Terminal, again with the virtual environment activated, run the below commands
to migrate changes.
9. In the VS Code Terminal, again with the virtual environment activated, run the development server with
python manage.py runserver and open a browser to http://127.0.0.1:8000/
10.In the url box of the browse, navigate to http://127.0.0.1:8000/registration/add_project to add the
projects into database. Similarly, check out http://127.0.0.1:8000/registration/project_list to view
projects.
DEPT.OFCSE,EPCET Page 44
FSD LAB 21CS62
Laboratory Component - 4:
1. 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.
2. Develop example Django app that performs CSV and PDF generation for any models created in
previous laboratory component.
#views.py
from .models import Student
from django.views.generic import ListView, DetailView
class StudentListView(ListView):
model = Student
template_name = 'course_registration/student_list.html'
context_object_name = 'students
class StudentDetailView(DetailView):
model = Student
template_name = 'course_registration/student_detail.html'
context_object_name = 'student'
DEPT.OFCSE,EPCET Page 45
FSD LAB 21CS62
#urls.py (course_registration/urls.py)
… (to indicate rest of code)
path('students/', views.StudentListView.as_view(), name='student_list'),
path('student/<int:pk>/', views.StudentDetailView.as_view(),
name='student_detail'),
…
DEPT.OFCSE,EPCET Page 46
FSD LAB 21CS62
#templates/course_registration/student_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Detail</title>
</head>
<body>
<h1>Student Detail</h1>
<p><strong>Name:</strong> {{ student.name }}</p>
<p><strong>ID:</strong> {{ student.id }}</p>
<p><strong>Date of Birth:</strong> {{ date_of_birth }}</p>
<p><strong>Email:</strong> {{ email }}</p>
<!-- Add more details as needed -->
</body>
</html>
5. In the VS Code Terminal, again with the virtual environment activated, run the development server with
python manage.py runserver and open a browser to http://127.0.0.1:8000/
DEPT.OFCSE,EPCET Page 47
FSD LAB 21CS62
DEPT.OFCSE,EPCET Page 48
FSD LAB 21CS62
p.showPage()
p.save()
# Move the buffer's cursor to the beginning
buffer.seek(0)
# Create an HTTP response with content type 'application/pdf'
response = HttpResponse(buffer.getvalue(), content_type='application/pdf')
# Set the content disposition header to specify the filename for download
response['Content-Disposition'] = 'attachment; filename="students.pdf"'
# Return the HTTP response containing the PDF file
return response
urlpatterns = [
path('generate_csv/', views.generate_csv, name='generate_csv'),
path('generate_pdf/', views.generate_pdf, name='generate_pdf'),
3. The myproject folder also contains a urls.py file, which is where URL routing is actually handled.
#urls.py (myproject/urls.py)
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("", include("myapp.urls")),
path("admin/", admin.site.urls),
path('', include('website_pages.urls')),
path('fruits_and_students/', include('fruits_and_students.urls')),
path('registration/', include('course_registration.urls')),
path('', include('generate.urls')),
]
4. In the myproject/settings.py file, locate the INSTALLED_APPS list and add the following entry, which
makes sure the project knows about the app so it can handle templating:
‘generate’
6. In the VS Code Terminal, again with the virtual environment activated, run the development server with
python manage.py runserver and open a browser to http://127.0.0.1:8000/
7. In the url box of the browse, navigate to http://127.0.0.1:8000/generate_pdf. Similarly, check out
http://127.0.0.1:8000/generate_csv.
DEPT.OFCSE,EPCET Page 50
FSD LAB 21CS62
Laboratory Component - 5:
1. Develop a registration page for student enrolment as done in Module 2 but without page refresh
using AJAX.
2. Develop a search application in Django using AJAX that displays courses enrolled by a student being
searched.
1. In the VS Code Terminal with your virtual environment activated, run the administrative utility's
startapp command in your myproject folder (where manage.py resides):
python manage.py startapp enrollment
3. Create a file, enrollment/urls.py, with the contents below. The urls.py file is where you specify patterns
to route different URLs to their appropriate views.
#urls.py (enrollment/urls.py)
from django.urls import path
from .views import register_student
urlpatterns = [
path('register/', register_student, name='register_student'),
]
4. The myproject folder also contains a urls.py file, which is where URL routing is actually handled.
#urls.py (myproject/urls.py)
…
path('', include('enrollment.urls')),
…
5. In the myproject/settings.py file, locate the INSTALLED_APPS list and add the following entry, which
makes sure the project knows about the app so it can handle templating:
‘enrollment’,
6. Create forms.py and add the following code.
#forms.py
from django import forms
class StudentRegistrationForm(forms.Form):
name = forms.CharField(label='Full Name', max_length=100)
email = forms.EmailField(label='Email')
course = forms.CharField(label='Course', max_length=100)
2. Inside the enrollment folder, create a folder named templates, and then another subfolder
named enrollment to match the app name (this two-tiered folder structure is typical Django
convention).
In the templates/enrollment folder, create a file named register.html with the contents below.
#register.html (enrollment/templates/enrollment/register.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Registration</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form id="registrationForm">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
<div id="message"></div>
DEPT.OFCSE,EPCET Page 52
FSD LAB 21CS62
<script>
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
$(document).ready(function () {
$('#registrationForm').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "register_student" %}',
data: $(this).serialize(),
success: function (response) {
if (response.success) {
$('#message').html('<p style="color: green;">' + response.message + '</p>');
$('#registrationForm').trigger('reset'); // Reset form if needed
} else {
$('#message').html('<p style="color: red;">' + JSON.stringify(response.errors) +
'</p>');
}
}
});
});
});
</script>
</body>
</html>
8. In the VS Code Terminal, again with the virtual environment activated, run the development server with
python manage.py runserver and open a browser to http://127.0.0.1:8000/
9.In the url box of the browse, navigate to http://127.0.0.1:8000/register. Uses AJAX to submit data
without refreshing the page. Just click on the Register button once details are entered.
DEPT.OFCSE,EPCET Page 53
FSD LAB 21CS62
1. In the VS Code Terminal with your virtual environment activated, run the administrative utility's
startapp command in your myproject folder (where manage.py resides):
python manage.py startapp course_search
DEPT.OFCSE,EPCET Page 54
FSD LAB 21CS62
3.Create a file, course_search/urls.py, with the contents below. The urls.py file is where you specify
patterns to route different URLs to their appropriate views.
#urls.py (course_search/urls.py)
from django.urls import path
from .views import search_courses
urlpatterns = [
path('search/', search_courses, name='search_courses'),
]
4.The myproject folder also contains a urls.py file, which is where URL routing is actually handled.
#urls.py (myproject/urls.py)
…
path(‘’, include(‘course_search.urls’)),
…
5. In the myproject/settings.py file, locate the INSTALLED_APPS list and add the following entry, which
makes sure the project knows about the app so it can handle templating:
‘course_search’,
6.Inside the course_search folder, create a folder named templates, and then another subfolder named
course_search to match the app name (this two-tiered folder structure is typical Django convention).
In the templates/course_search folder, create a file named search.html with the contents below.
#search.html (course_search/templates/course_search/search.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search Courses</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('#search-form').submit(function(event) {
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: '/search/',
type: 'get',
data: formData,
dataType: 'json',
success: function(response) {
if (response.courses) {
var coursesHtml = '';
response.courses.forEach(function(course) {
coursesHtml += '<li>' + course.name + ' (' + course.course_id + ')</li>';
});
DEPT.OFCSE,EPCET Page 55
FSD LAB 21CS62
$('#courses-list').html(coursesHtml);
} else {
$('#courses-list').html('<li>No courses found</li>');
}
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
});
});
</script>
</head>
<body>
<h1>Search Courses by Student</h1>
<form id="search-form" method="get">
<input type="text" name="query" placeholder="Enter student name">
<button type="submit">Search</button>
</form>
<ul id="courses-list"></ul>
</body>
</html>
8. In the VS Code Terminal, again with the virtual environment activated, run the development
server with python manage.py runserver and open a browser to http://127.0.0.1:8000/
9. In the url box of the browse, navigate to http://127.0.0.1:8000/search. Uses AJAX to retrieve data
without refreshing the page. Just click on the Search button once details are entered.
DEPT.OFCSE,EPCET Page 56
FSD LAB 21CS62
DEPT.OFCSE,EPCET Page 57