FSD Lab Manual
FSD Lab Manual
FSD Lab Manual
VI- Semester
Prepared by
Dr. Harish kumar B T
Prof. Prashanth Kumar
Prof. Vidyashree A L
BANGALORE INSTITUTE OF TECHNOLOGY
(Affiliated to Visvesvaraya Technological University – VTU )
K.R. Road, V.V. Puram, Bengaluru – 560 004. Phone: 26613237/26615865 Fax:
22426796
Vision
Establish and develop the Institute as the Centre of higher learning, ever abreast with expanding
horizon of knowledge in the field of Engineering and Technology with entrepreneurial thinking,
leadership excellence for life-long success and solve societal problems.
Mission
1. Provide high quality education in the Engineering disciplines from the undergraduate
through doctoral levels with creative academic and professional programs.
2. Develop the Institute as a leader in Science, Engineering, Technology, Management and
Research and apply knowledge for the benefit of society.
3. Establish mutual beneficial partnerships with Industry, Alumni, Local, State and Central
Governments by Public Service Assistance and Collaborative Research.
4. Inculcate personality development through sports, cultural and extracurricular activities
and engage in social, economic and professional challenges.
BANGALORE INSTITUTE OF TECHNOLOGY
(Affiliated to Visvesvaraya Technological University – VTU )
K.R. Road, V.V. Puram, Bengaluru – 560 004. Phone: 26613237/26615865 Fax:
22426796
VISION:
To be a center of excellence in computer engineering education, empowering graduates as
highly skilled professionals.
MISSION:
1. To provide a platform for effective learning with emphasis on technical excellence.
2. To train the students to meet current industrial standards and adapt to emerging
technologies.
3. To instill the drive for higher learning and research initiatives.
4. To inculcate the qualities of leadership and Entrepreneurship.
1. The graduates of the program will have the ability to build software products by
applying theoretical concepts and programming skills.
2. The graduates of the program will have the ability to pursue higher
Program Outcomes
CO1
CO2
21CS
CO3
62
CO4
CO5
Full Stack Development Laboratory
1. a. Installation of Python, Django and Visual Studio code editors can be demonstrated.
b. Creation of virtual environment, Django project and App should be demonstrated
c. Develop a Django app that displays current date and time in server
d. 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.
2. a. Develop a simple Django app that displays an unordered list of fruits and ordered list of
selected students for an event
b. 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.
c. 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.
3. a. For student and course models created in Lab experiment for Module2, register admin
interfaces, perform migrations and illustrate data entry through admin forms.
b. Develop a Model form for student that contains his topic chosen for project, languages
used and duration with a model called project.
4. a. 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.
b. Develop example Django app that performs CSV and PDF generation for any models
created in previous 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.
21CS62 Full Stack Development Laboratory
SCHEDULE OF EXPERIMENTS
Display Current Date and Time four hours ahead and four hours
5 Week5
before in server.
Django app that displays an unordered list of fruits and ordered list of
6 Week6
selected students for an event
Inherit this layout.html and create 3 additional pages: contact us,
7 Week7
About Us and Home page of any website.
Django app that performs student registration to a course. It should
8 also display list of students registered for any selected course. Create Week8
students and course as models with enrolment as ManyToMany field.
a. For student and course models created in Lab experiment for
Module2, register admin interfaces, perform migrations and illustrate
9 data entry through admin forms Week9
b. Develop a Model form for student that contains his topic chosen
for project, languages used and duration with a model called project.
For students enrolment developed in Module 2, create a generic class Week10
10 view which 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 Week11
11 for any models created in previous laboratory component.
LABORATORY
General Lab Guidelines:
1. Conduct yourself in a responsible manner at all times in the laboratory. Intentional
misconduct will lead to exclusion from the lab.
2. Do not wander around, or distract other students, or interfere with the laboratory
experiments of other students.
3. Read the handout and procedures before starting the experiments. Follow all written
and verbal instructions carefully.
4. If you do not understand the procedures, ask the instructor or teaching assistant.
Attendance in all the labs is mandatory, absence permitted only with prior permission
from the Class teacher.
5. The workplace has to be tidy before, during and after the experiment.
6. Do not eat food, drink beverages or chew gum in the laboratory.
7. Every student should know the location and operating procedures of all Safety
equipment including First Aid Kit and Fire extinguisher.
DO’S:-
1. An ID card is a must.
2. Keep your belongings in a designated area.
3. Sign the log book when you enter/leave the laboratory.
4. Records have to be submitted every week for evaluation.
5. The program to be executed in the respective lab session has to be written in the lab
observation copy beforehand.
6. After the lab session, shut down the computers.
7. Report any problem in system (if any) to the person in-charge
DON'TS:-
1. Do not insert metal objects such as clips, pins and needles into the computer
casings(They may cause fire) and should not attempt to repair, open, tamper or
interfere with any of the computer, printing, cabling, or other equipment in the
laboratory.
2. Do not change the system settings and keyboard keys.
3. Do not upload, delete or alter any software/ system files on laboratory computers.
4. No additional material should be carried by the students during regular labs.
CSS (Cascading Style Sheets): Used for styling the appearance of web pages.
Back-End Technologies:
Server-side languages like JavaScript (Node.js), Python (Django, Flask), Ruby (Ruby
on Rails), Java (Spring Boot), or PHP (Laravel), C#(.Net Framework), java(Servlets)
Web servers like Apache or Nginx or IIS or Tomcat or Caddy(with built in support for
https) for handling HTTP requests.
Command-line tools for tasks like package management (npm for Node.js, pip for
Python, nugget for .Net), running servers, and deployment.
Important STACKS
MEAN Stack
MERN Stack
Django Stack
LAMP
WAMP
Why Django?
Rounded Solution
Great Exposure
Complete Ownership
Security (Prevention of threats such as SQL injection, cross-site scripting (XSS), cross-
site request forgery (CSRF), and clickjacking by providing {% csrf_token %} django
tag to be included inside the form.
This token generates a hidden input field containing a unique CSRF token. This
token is then validated by Django when the form is submitted, ensuring that the
request originated from the same site and protecting against CSRF attacks.
What is Django
Django is a free and open source web application framework which offers fast and
effective dynamic website development.
Framework
A framework is a pre-built collection of libraries, modules, and tools that provides a
structured approach to developing software applications.
Django Evolution
1. Write a Web application from scratch.
3. Realize the application from step 1 shares much in common with the application from step
2.
Django MVT
The MVT is a software design pattern which includes three important components Model,
View and Template.
The Model helps to handle database. It is a data access layer which handles the data.
The Template is a presentation layer which handles User Interface part completely.
The View is used to execute the business logic and interact with a model to carry data
and renders a template.
Characteristics of Django
Loosely Coupled − Django helps you to make each element of its stack independent
of the others.
Less code - Ensures effective development
Not repeated- Everything should be developed in precisely one place instead of
repeating it again
Fast development- Django's offers fast and reliable application development.
Consistent design - Django maintains a clean design and makes it easy to follow the
best web development practices.
A Python Virtual Environment is an isolated space where you can work on your Python
projects, separately from your system-installed Python.
You can set up your own libraries and dependencies without affecting the system
Python.
It allows you to have multiple Python environments with different versions of Python
and different sets of installed packages on the same system.
It is generally good to have one new virtual environment for every Python-based
project you work on
You can change the system python version, django version and other dependencies
without affecting the project python version, django versions and dependencies
https://www.python.org/downloads/
https://code.visualstudio.com/
Creating system root folder, project root project folder, creating virtual env inside
project root folder.
Create a system root folder with the name BIT_CSE_FDP in the file system (inside any
preferred drive).
Create a project root folder inside BIT_CSE_FDP with the name “hello_world”
(assuming we are doing simple hello world program)
Open cmd inside “hello_world”
Create virtual env inside “hello_world” with the name “hello_world_venv”
Run “code .” in the cmd prompt to launch the project folder “hello_world” in VS
code.
or
Launch VS code from the task bar, goto file menu navigate and open “hello_world”
Command palette (select your venv as python interpreter for your project root folder)
The command presents a list of available interpreters that VS Code can locate
automatically. From the list, select the virtual environment in your project folder that
starts with ./env or .\env:
Create the django project with the name “hello_world_proj” inside the project root
folder “hello_world”
SAMPLE PROGRAMS
Helloworld
views.py
from django.http import HttpResponse
from django.shortcuts import render
def hello(request):
resp="<h1>Hello World!!!!</h1>"
return HttpResponse(resp)
urls.py
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/',hello),
]
OUTPUT
GreetUser
greet.html
<!DOCTYPE html>
<html>
<head>
<title>Greet App</title>
</head>
<body>
<h1>{{user}} Good afternoon! Welcome to FDP on Full stack development</h1>
</body>
</html>
views.py
from django.shortcuts import render
def greet(request,user):
uname=user
d={'user':user}
return render(request,'greet.html',d)
urls.py
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('greet/<str:user>/',greet),
OUTPUT
Vowel Count
StudentlistApp
views.py
from django.http import HttpResponse
from django.shortcuts import render
views.py
from django.http import HttpResponse
from django.shortcuts import render
def VC(request,s):
v_cnt=0
c_cnt=0
v_dict={} #v_dict=dict()
c_dict={}
for letter in s:
if letter.isalpha():
if letter in "aeiouAEIOU":
v_cnt=v_cnt+1
v_dict[letter]=v_dict.get(letter,0)+1
else:
c_cnt=c_cnt+1
c_dict[letter]=c_dict.get(letter,0)+1
resp="<h1>Vowel Count=%d</h1><h1>Cons Count=%d</h1>"%(v_cnt,c_cnt)
resp+="<h1>Vowel Count Frequency</h1>"
for key,val in v_dict.items():
resp+="<h3>"+key+":"+str(val)+"</h3>"
resp+="<h1>Cons Count Frequency</h1>"
for key,val in c_dict.items():
resp+="<h3>"+key+":"+str(val)+"</h3>"
return HttpResponse(resp)
urls.py
from django.contrib import admin
from django.urls import path
OUTPUT
LAB PROGRAMS
PROGRAM 1
1.1 Installation of Python, Django and Visual Studio code editors can be demonstrated.
1.2 Develop a Django app that displays current date and time in server
views.py
from django.shortcuts import render
import datetime
from django.http import HttpResponse
# Create your views here.
def cdt(request):
dt=datetime.datetime.now()
resp="<h1>Current Date and Time is %s<h1>"%(dt)
return HttpResponse(resp)
urls.py
from django.contrib import admin
from django.urls import path
from scdtApp.views import cdt
urlpatterns = [
path('admin/', admin.site.urls),
path('currentDT/',cdt),
]
OUTPUT
1.3 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.
views.py
from django.shortcuts import render
import datetime
from django.http import HttpResponse
# Create your views here.
def aheadtime(request):
dt=datetime.datetime.now()+datetime.timedelta(hours=4)
resp="<html><head><title>Current Time Ahead by
4hrs</title></head><body><h1>Current date and Time ahead by 4 hrs is %s
</h1></body></html>"%(dt)
return HttpResponse(resp)
urls.py
from django.contrib import admin
from django.urls import path
from scdt_a4App.views import aheadtime
urlpatterns = [
path('admin/', admin.site.urls),
path('ahead/',aheadtime),
]
OUTPUT
views.py
from django.shortcuts import render
import datetime
from django.http import HttpResponse
# Create your views here.
def beforetime(request):
dt=datetime.datetime.now()+datetime.timedelta(hours=-4)
resp="<h1>Current Server Date and Time Before 4hrs is %s</h1>"%(dt)
return HttpResponse(resp)
urls.py
from django.contrib import admin
from django.urls import path
from scdt_b4App.views import beforetime
urlpatterns = [
path('admin/', admin.site.urls),
path('before/',beforetime),
]
OUTPUT
views.py
from django.shortcuts import render
import datetime
from django.http import HttpResponse
# Create your views here.
def ahead(request):
dt=datetime.datetime.now()+datetime.timedelta(hours=5)
resp="<h1>Current date and time ahead by 5hrs is %s</h1>"%(dt)
return HttpResponse(resp)
def before(request):
dt=datetime.datetime.now()+datetime.timedelta(hours=-5)
resp="<h1>Current date and time before by 5hrs is %s</h1>"%(dt)
return HttpResponse(resp)
urls.py
from django.contrib import admin
from django.urls import path
from scdt_abApp.views import ahead, before
urlpatterns = [
path('admin/', admin.site.urls),
path('ahead/',ahead),
path('before/',before),
]
OUTPUT
views.py
from django.shortcuts import render
import datetime
from django.http import HttpResponse
def scdt_dyn(request,t):
dt=datetime.datetime.now()+datetime.timedelta(hours=t)
resp="<h1>Current Date and Time Ahead by %d hrs is %s</h1>"%(t,dt)
return HttpResponse(resp)
urls.py
from django.contrib import admin
from django.urls import path
from scdt_dynApp.views import scdt_dyn
urlpatterns = [
path('admin/', admin.site.urls),
path('dyntime/<int:t>',scdt_dyn),
]
OUTPUT
views.py
import datetime
from django.http import HttpResponse
from django.shortcuts import render
def scdt(request,s):
t=int(s)
dt=datetime.datetime.now()+datetime.timedelta(hours=t)
if t<0:
resp="<h1>Current Date and Time Behind %d hrs is %s</h1>"%(t,dt)
elif t>0:
resp="<h1>Current Date and Time ahead by %d hrs is %s</h1>"%(t,dt)
else:
resp="<h1>There is no change in current date and time</h1>"
return HttpResponse(resp)
urls.py
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('dynamicTime/<str:s>/',scdt),
]
OUTPUT
PROGRAM 2
2.1 Develop a simple Django app that displays an unordered list of fruits and ordered list of
selected students for an event.
fruits_student.html
<!DOCTYPE html>
<html>
<head>
<style>
#a1{background-color: lightblue;color:brown}
#a2{background-color:blue;color:yellow}
</style>
<title>
Unordered Fruits and Ordered Students
</title>
</head>
<body>
<h1 id="a1">Unordered List of Fruits</h1>
<ul>
{% for fruit in fruitList %}
<li>{{fruit}}</li>
{% endfor %}
</ul>
<h1 id="a2">Ordered List of Students Selected for an Event</h1>
<ol>
{% for student in studentList %}
<li>{{student}}</li>
{% endfor %}
</ol>
</body>
</html>
views.py
from django.shortcuts import render
def fruit_student(request):
fruitList=['Mango','Kiwi','Banana','Apple','Grapes']
studentList=['Rama','Chetan','Kumar','Harish','Geetha']
return
render(request,'fruit_student.html',{'fruitList':fruitList,'studentList':sorted(studentList)})
urls.py
from django.contrib import admin
from django.urls import path
from FruitsApp.views import fruit_student
urlpatterns = [
path('admin/', admin.site.urls),
path('fruits/',fruit_student),
]
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'fruitsapp',
]
OUTPUT
2.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.
layout.html
<!DOCTYPE html>
<html>
<head>
<style>
nav{background-color: lightblue;padding: 15px;}
</style>
<title>
{% block title %} {% endblock %}
</title>
</head>
<body>
<nav>
<a href="/home/">HOME</a>
<a href="/contactus/">CONTACT US</a>
<a href="/aboutus/">ABOUT US</a>
</nav>
<section>
{% block content %} {% endblock %}
</section>
<footer>
<hr>
© Designed and Developed by Dr. Harish Kumar B T, CSE, BIT, Bangalore-04
</footer>
</body>
</html>
home.html
{% extends 'layout.html' %}
{% block title %} HOME Page {% endblock %}
{% block content %}
<h1>This is my home page</h1>
{% endblock %}
about.html
{% extends 'layout.html' %}
{% block title %} ABOUT PAGE {% endblock %}
{% block content %}
<h1>About Us</h1>
<p>Dr. Harish Kumar B T, Asso. Prof, Dept of CSE, BIT</p>
{% endblock %}
contactus.html
{% extends 'layout.html' %}
{% block title %} Contact us {% endblock %}
{% block content %}
<h1>Contact us</h1>
<p>Name: Dr. Harish Kumar B T</p>
<p>Designation:Asso. Prof </p>
<p>Mobile: 9980119894</p>
<p>Email: [email protected]</p>
{% endblock %}
views.py
from django.shortcuts import render
def home(request):
return render(request,'home.html')
def contactus(request):
return render(request,'contactus.html')
def aboutus(request):
return render(request,'about.html')
urls.py
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('',home),
path('contactus/',contactus),
path('aboutus/',aboutus),
path('home/',home),
]
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'layoutApp',
]
OUTPUT
2.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.
basicTemplate.html
<!DOCTYPE html>
<html>
<head>
<style>
nav{background-color: lightblue;padding: 15px; }
nav a {
color: #fff; /* Text color */
text-decoration: none; /* Remove underline */
padding: 10px 20px; /* Padding around each link */
margin: 0px 10px; /* Spacing between links */
border-radius: 5px; /* Rounded corners */
background-color: #555;
flex-wrap: wrap;
nav a:hover {
background-color:aqua;/* Background color on hover */
}
ul {
list-style: none;
margin: 0;
padding: 0;
display: flex; /* Use flexbox */
flex-wrap: wrap; /* Allow items to wrap to the next line */
flex-direction: row; /* Display items in a column */
}
li {
margin-right: 20px;
margin-bottom: 25px;
}
</style>
<title>
{% block title %} {% endblock %}
</title>
</head>
<body>
<center> <h1 style="background-color: blue;color:yellow"> STUDENT COURSE
REGISTRATION PORTAL</h1></center>
<nav>
<ul>
<li> <a href="/home/">HOME</a></li>
<li> <a href="/studentlist/">STUDENT LIST</a></li>
<li> <a href="/courselist/">COURSE LIST</a> </li>
<li> <a href="/register/">REGISTER</a></li>
<li> <a href="/enrolledlist/">ENROLLED LIST</a></li>
<li> <a href="/addproject/">ADD PROJECT</a></li>
<li><a href="/genericlistviewstudent/">GENERIC STUDENT LIST VIEW</a></li>
<li> <a href="/download_course_table_as_csv/">DOWNLOAD COURSE AS
CSV</a> </li>
<li> <a href="/download_course_table_as_pdf/">DWONLOAD COURSE AS
PDF</a></li>
</ul>
</nav>
<section>
{% block content %} {% endblock %}
</section>
<footer>
<hr/>
<center>
© Designed and Developeb by Dr. Harish Kumar B T, Dept. of CSE, BIT,
Bangalore-04
</center>
</footer>
</body>
</html>
home.html
{% extends 'basicTemplate.html' %}
{% block title %} Home Page {% endblock %}
{% block content %}
{% endblock %}
studentlist.html
{% extends 'basicTemplate.html' %}
{% block title %} Student List {% endblock %}
{% block content%}
<h1>Student List</h1>
<table border="1">
<tr>
<th>
USN
</th>
<th>
NAME
</th>
<th>
SEM
</th>
</tr>
{% for s in student_list %}
<tr>
<td>{{s.usn}}</td>
<td>{{s.name}}</td>
<td>{{s.sem}}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
courselist.html
{% extends 'basicTemplate.html' %}
{% block title %} Course List {% endblock %}
{% block content%}
<h1> Course List</h1>
<table border="1">
<tr>
<th>
Sub Code
</th>
<th>
Sub Name
</th>
<th>
Credits
</th>
</tr>
{% for c in course_list %}
<tr>
<td>{{c.courseCode}}</td>
<td>{{c.courseName}}</td>
<td>{{c.courseCredits}}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
enrolledlist.html
{% extends 'basicTemplate.html' %}
{% block title %} Course Registration Details {% endblock %}
{% block content %}
<tr>
<th>
USN
</th>
<th>
NAME
</th>
<th>
SEM
</th>
</tr>
{% for s in student_list %}
<tr>
<td>{{s.usn}}</td>
<td>{{s.name}}</td>
<td>{{s.sem}}</td>
</tr>
{% endfor %}
</table>
{% endif %}
</form>
{% endblock %}
register.html
{% extends 'basicTemplate.html' %}
{% block title %} Course Register Page {% endblock %}
{% block content %}
<h1> Student Course Registration</h1>
<form method="POST" action="">
{% csrf_token %}
Select USN:
<select name="student">
{% for s in student_list %}
<option value="{{s.id}}">{{s.usn}}</option>
{% endfor %}
</select>
Select Course:
<select name="course">
{% for c in course_list %}
<option value="{{c.id}}">{{c.courseCode}}</option>
{% endfor %}
</select>
<input type="submit" value="ENROLL"/>
</form>
{% endblock %}
models.py
from django.db import models
from django.forms import ModelForm
class course(models.Model):
courseCode=models.CharField(max_length=10)
courseName=models.CharField(max_length=50)
courseCredits=models.IntegerField()
def __str__(self):
return self.courseCode+" "+self.courseName+" "+str(self.courseCredits)
class student(models.Model):
usn=models.CharField(max_length=10)
name=models.CharField(max_length=40)
sem=models.IntegerField()
courses=models.ManyToManyField(course,related_name='student_set')
def __str__(self):
return self.usn+" "+self.name+" "+str(self.sem)
Open python interactive console in VS code terminal by giving the following command
python manage.py shell
In interactive python console import the model student and course as shown below
from studCourseRegApp.models import student,course
Make the list of students write a for loop and save each student object the student table as
show below
studList=[s1,s2,s3,s4,s5,s6]
for stud in studList:
... stud.save()
Open Sqlite DB in VS code and check the student and Course Table [Every time you update
the table close and open the Sqlite DB to view the updated data]
views.py
from django.http import HttpResponse
from django.shortcuts import render
from studCourseRegApp.models import student,course, projectForm
def studentlist(request):
s=student.objects.all()
return render(request,'studentlist.html',{'student_list':s})
def courselist(request):
c=course.objects.all()
return render(request,'courselist.html',{'course_list':c})
def register(request):
if request.method=="POST":
sid=request.POST.get("student")
cid=request.POST.get("course")
studentobj=student.objects.get(id=sid)
courseobj=course.objects.get(id=cid)
res=studentobj.courses.filter(id=cid)
if res:
resp="<h1>Student with usn %s has already enrolled for the
%s<h1>"%(studentobj.usn,courseobj.courseCode)
return HttpResponse(resp)
studentobj.courses.add(courseobj)
resp="<h1>student with usn %s successfully enrolled for the course with sub code
%s</h1>"%(studentobj.usn,courseobj.courseCode)
return HttpResponse(resp)
else:
studentlist=student.objects.all()
courselist=course.objects.all()
return render(request,'register.html',{'student_list':studentlist,'course_list':courselist})
def enrolledStudents(request):
if request.method=="POST":
cid=request.POST.get("course")
courseobj=course.objects.get(id=cid)
studentlistobj=courseobj.student_set.all()
return render(request,'enrolledlist.html',{'course':courseobj,'student_list':studentlistobj})
else:
courselist=course.objects.all()
return render(request,'enrolledlist.html',{'Course_List':courselist})
urls.py
from django.contrib import admin
from django.urls import path
from studCourseRegApp.views import home, studentlist,courselist,register,enrolledStudents
urlpatterns = [
path('secretadmin/', admin.site.urls),
path('',home),
path('home/',home),
path('studentlist/',studentlist),
path('courselist/',courselist),
path('register/',register),
path('enrolledlist/',enrolledStudents),
]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'studCourseRegApp',
]
OUTPUT
PROGRAM 3
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.
basicTemplate.html
<!DOCTYPE html>
<html>
<head>
<style>
nav{background-color: lightblue;padding: 15px; }
nav a {
color: #fff; /* Text color */
text-decoration: none; /* Remove underline */
nav a:hover {
background-color:aqua;/* Background color on hover */
}
ul {
list-style: none;
margin: 0;
padding: 0;
display: flex; /* Use flexbox */
flex-wrap: wrap; /* Allow items to wrap to the next line */
flex-direction: row; /* Display items in a column */
}
li {
margin-right: 20px;
margin-bottom: 25px;
}
</style>
<title>
{% block title %} {% endblock %}
</title>
</head>
<body>
<center> <h1 style="background-color: blue;color:yellow"> STUDENT COURSE
REGISTRATION PORTAL</h1></center>
<nav>
<ul>
<li> <a href="/home/">HOME</a></li>
<li> <a href="/studentlist/">STUDENT LIST</a></li>
<li> <a href="/courselist/">COURSE LIST</a> </li>
<li> <a href="/register/">REGISTER</a></li>
<li> <a href="/enrolledlist/">ENROLLED LIST</a></li>
<li> <a href="/addproject/">ADD PROJECT</a></li>
<li><a href="/genericlistviewstudent/">GENERIC STUDENT LIST VIEW</a></li>
<li> <a href="/download_course_table_as_csv/">DOWNLOAD COURSE AS
CSV</a> </li>
<li> <a href="/download_course_table_as_pdf/">DWONLOAD COURSE AS
PDF</a></li>
</ul>
</nav>
<section>
{% block content %} {% endblock %}
</section>
<footer>
<hr/>
<center>
© Designed and Developeb by Dr. Harish Kumar B T, Dept. of CSE, BIT,
Bangalore-04
</center>
</footer>
</body>
</html>
home.html
{% extends 'basicTemplate.html' %}
{% block title %} Home Page {% endblock %}
{% block content %}
{% endblock %}
studentlist.html
{% extends 'basicTemplate.html' %}
{% block title %} Student List {% endblock %}
{% block content%}
<h1>Student List</h1>
<table border="1">
<tr>
<th>
USN
</th>
<th>
NAME
</th>
<th>
SEM
</th>
</tr>
{% for s in student_list %}
<tr>
<td>{{s.usn}}</td>
<td>{{s.name}}</td>
<td>{{s.sem}}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
courselist.html
{% extends 'basicTemplate.html' %}
{% block title %} Course List {% endblock %}
{% block content%}
<h1> Course List</h1>
<table border="1">
<tr>
<th>
Sub Code
</th>
<th>
Sub Name
</th>
<th>
Credits
</th>
</tr>
{% for c in course_list %}
<tr>
<td>{{c.courseCode}}</td>
<td>{{c.courseName}}</td>
<td>{{c.courseCredits}}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
enrolledlist.html
{% extends 'basicTemplate.html' %}
{% block title %} Course Registration Details {% endblock %}
{% block content %}
<tr>
<th>
USN
</th>
<th>
NAME
</th>
<th>
SEM
</th>
</tr>
{% for s in student_list %}
<tr>
<td>{{s.usn}}</td>
<td>{{s.name}}</td>
<td>{{s.sem}}</td>
</tr>
{% endfor %}
</table>
{% endif %}
</form>
{% endblock %}
register.html
{% extends 'basicTemplate.html' %}
{% block title %} Course Register Page {% endblock %}
{% block content %}
<h1> Student Course Registration</h1>
<form method="POST" action="">
{% csrf_token %}
Select USN:
<select name="student">
{% for s in student_list %}
<option value="{{s.id}}">{{s.usn}}</option>
{% endfor %}
</select>
Select Course:
<select name="course">
{% for c in course_list %}
<option value="{{c.id}}">{{c.courseCode}}</option>
{% endfor %}
</select>
<input type="submit" value="ENROLL"/>
</form>
{% endblock %}
projectreg.html
{% extends 'basicTemplate.html' %}
{% block title %} Project Details Registration {% endblock %}
{% block content %}
<form method="POST" action="">
{% csrf_token %}
<table border="1">
{{ form.as_table }}
<tr>
<td>
<input type="submit" value="Add Project"/>
</td>
</tr>
</table>
</form>
{% endblock %}
admin.py
from django.contrib import admin
#admin.site.register(student)
#admin.site.register(course)
admin.site.site_header='FDP ON Django'
admin.site.site_title='FDP ON Django'
@admin.register(student)
class studentAdmin(admin.ModelAdmin):
list_display=('usn','name')
ordering=('usn',)
search_fields=('name',)
@admin.register(course)
class courseAdmin(admin.ModelAdmin):
list_display=('courseCode','courseName')
ordering=('courseCode',)
search_fields=('courseName',)
models.py
from django.db import models
from django.forms import ModelForm
class course(models.Model):
courseCode=models.CharField(max_length=10)
courseName=models.CharField(max_length=50)
courseCredits=models.IntegerField()
def __str__(self):
return self.courseCode+" "+self.courseName+" "+str(self.courseCredits)
class student(models.Model):
usn=models.CharField(max_length=10)
name=models.CharField(max_length=40)
sem=models.IntegerField()
courses=models.ManyToManyField(course,related_name='student_set')
def __str__(self):
return self.usn+" "+self.name+" "+str(self.sem)
class projectReg(models.Model):
student=models.ForeignKey(student,on_delete=models.CASCADE)
ptitle=models.CharField(max_length=30)
planguage=models.CharField(max_length=30)
pduration=models.IntegerField()
class projectForm(ModelForm):
required_css_class="required"
class Meta:
model=projectReg
fields=['student','ptitle','planguage','pduration']
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('studCourseRegApp', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='projectReg',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('ptitle', models.CharField(max_length=30)),
('planguage', models.CharField(max_length=30)),
('pduration', models.IntegerField()),
('student', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
to='studCourseRegApp.student')),
],
),
]
views.py
from django.http import HttpResponse
from django.shortcuts import render
from studCourseRegApp.models import student,course, projectForm
def studentlist(request):
s=student.objects.all()
return render(request,'studentlist.html',{'student_list':s})
def courselist(request):
c=course.objects.all()
return render(request,'courselist.html',{'course_list':c})
def register(request):
if request.method=="POST":
sid=request.POST.get("student")
cid=request.POST.get("course")
studentobj=student.objects.get(id=sid)
courseobj=course.objects.get(id=cid)
res=studentobj.courses.filter(id=cid)
if res:
resp="<h1>Student with usn %s has already enrolled for the
%s<h1>"%(studentobj.usn,courseobj.courseCode)
return HttpResponse(resp)
studentobj.courses.add(courseobj)
resp="<h1>student with usn %s successfully enrolled for the course with sub code
%s</h1>"%(studentobj.usn,courseobj.courseCode)
return HttpResponse(resp)
else:
studentlist=student.objects.all()
courselist=course.objects.all()
return render(request,'register.html',{'student_list':studentlist,'course_list':courselist})
def enrolledStudents(request):
if request.method=="POST":
cid=request.POST.get("course")
courseobj=course.objects.get(id=cid)
studentlistobj=courseobj.student_set.all()
return render(request,'enrolledlist.html',{'course':courseobj,'student_list':studentlistobj})
else:
courselist=course.objects.all()
return render(request,'enrolledlist.html',{'Course_List':courselist})
def add_project(request):
if request.method=="POST":
form=projectForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse("<h1>Project Data Successfully saved</h1>")
else:
urls.py
from django.contrib import admin
from django.urls import path
from studCourseRegApp.views import enrolledStudentsUsingAjax, generateCSV, home,
registerAjax, studentlist,courselist,register,enrolledStudents,add_project,
urlpatterns = [
path('secretadmin/', admin.site.urls),
path('',home),
path('home/',home),
path('studentlist/',studentlist),
path('courselist/',courselist),
path('register/',register),
path('enrolledlist/',enrolledStudents),
path('addproject/',add_project),
]
settings.py(only one change inside installed apps add studCourseRegApp )
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'studCourseRegApp',
]
OUTPUT
3.2 . Develop a Model form for student that contains his topic chosen for project, languages
used and duration with a model called project.
basicTemplate.html
<!DOCTYPE html>
<html>
<head>
<style>
nav{background-color: lightblue;padding: 15px; }
nav a {
color: #fff; /* Text color */
text-decoration: none; /* Remove underline */
padding: 10px 20px; /* Padding around each link */
margin: 0px 10px; /* Spacing between links */
border-radius: 5px; /* Rounded corners */
background-color: #555;
flex-wrap: wrap;
nav a:hover {
background-color:aqua;/* Background color on hover */
}
ul {
list-style: none;
margin: 0;
padding: 0;
display: flex; /* Use flexbox */
flex-wrap: wrap; /* Allow items to wrap to the next line */
flex-direction: row; /* Display items in a column */
}
li {
margin-right: 20px;
margin-bottom: 25px;
}
</style>
<title>
{% block title %} {% endblock %}
</title>
</head>
<body>
<center> <h1 style="background-color: blue;color:yellow"> STUDENT COURSE
REGISTRATION PORTAL</h1></center>
<nav>
<ul>
<li> <a href="/home/">HOME</a></li>
<li> <a href="/studentlist/">STUDENT LIST</a></li>
<li> <a href="/courselist/">COURSE LIST</a> </li>
<li> <a href="/register/">REGISTER</a></li>
<li> <a href="/enrolledlist/">ENROLLED LIST</a></li>
<li> <a href="/addproject/">ADD PROJECT</a></li>
</body>
</html>
home.html
{% extends 'basicTemplate.html' %}
{% block title %} Home Page {% endblock %}
{% block content %}
{% endblock %}
studentlist.html
{% extends 'basicTemplate.html' %}
{% block title %} Student List {% endblock %}
{% block content%}
<h1>Student List</h1>
<table border="1">
<tr>
<th>
USN
</th>
<th>
NAME
</th>
<th>
SEM
</th>
</tr>
{% for s in student_list %}
<tr>
<td>{{s.usn}}</td>
<td>{{s.name}}</td>
<td>{{s.sem}}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
courselist.html
{% extends 'basicTemplate.html' %}
{% block title %} Course List {% endblock %}
{% block content%}
<h1> Course List</h1>
<table border="1">
<tr>
<th>
Sub Code
</th>
<th>
Sub Name
</th>
<th>
Credits
</th>
</tr>
{% for c in course_list %}
<tr>
<td>{{c.courseCode}}</td>
<td>{{c.courseName}}</td>
<td>{{c.courseCredits}}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
enrolledlist.html
{% extends 'basicTemplate.html' %}
{% block title %} Course Registration Details {% endblock %}
{% block content %}
<tr>
<th>
USN
</th>
<th>
NAME
</th>
<th>
SEM
</th>
</tr>
{% for s in student_list %}
<tr>
<td>{{s.usn}}</td>
<td>{{s.name}}</td>
<td>{{s.sem}}</td>
</tr>
{% endfor %}
</table>
{% endif %}
</form>
{% endblock %}
register.html
{% extends 'basicTemplate.html' %}
{% block title %} Course Register Page {% endblock %}
{% block content %}
<h1> Student Course Registration</h1>
<form method="POST" action="">
{% csrf_token %}
Select USN:
<select name="student">
{% for s in student_list %}
<option value="{{s.id}}">{{s.usn}}</option>
{% endfor %}
</select>
Select Course:
<select name="course">
{% for c in course_list %}
<option value="{{c.id}}">{{c.courseCode}}</option>
{% endfor %}
</select>
<input type="submit" value="ENROLL"/>
</form>
{% endblock %}
projectreg.html
{% extends 'basicTemplate.html' %}
{% block title %} Project Details Registration {% endblock %}
{% block content %}
<form method="POST" action="">
{% csrf_token %}
<table border="1">
{{ form.as_table }}
<tr>
<td>
<input type="submit" value="Add Project"/>
</td>
</tr>
</table>
</form>
{% endblock %}
models.py
from django.db import models
from django.forms import ModelForm
class course(models.Model):
courseCode=models.CharField(max_length=10)
courseName=models.CharField(max_length=50)
courseCredits=models.IntegerField()
def __str__(self):
return self.courseCode+" "+self.courseName+" "+str(self.courseCredits)
class student(models.Model):
usn=models.CharField(max_length=10)
name=models.CharField(max_length=40)
sem=models.IntegerField()
courses=models.ManyToManyField(course,related_name='student_set')
def __str__(self):
return self.usn+" "+self.name+" "+str(self.sem)
class projectReg(models.Model):
student=models.ForeignKey(student,on_delete=models.CASCADE)
ptitle=models.CharField(max_length=30)
planguage=models.CharField(max_length=30)
pduration=models.IntegerField()
class projectForm(ModelForm):
required_css_class="required"
class Meta:
model=projectReg
fields=['student','ptitle','planguage','pduration']
views.py
from django.http import HttpResponse
from django.shortcuts import render
from studCourseRegApp.models import student,course, projectForm
def studentlist(request):
s=student.objects.all()
return render(request,'studentlist.html',{'student_list':s})
def courselist(request):
c=course.objects.all()
return render(request,'courselist.html',{'course_list':c})
def register(request):
if request.method=="POST":
sid=request.POST.get("student")
cid=request.POST.get("course")
studentobj=student.objects.get(id=sid)
courseobj=course.objects.get(id=cid)
res=studentobj.courses.filter(id=cid)
if res:
resp="<h1>Student with usn %s has already enrolled for the
%s<h1>"%(studentobj.usn,courseobj.courseCode)
return HttpResponse(resp)
studentobj.courses.add(courseobj)
resp="<h1>student with usn %s successfully enrolled for the course with sub code
%s</h1>"%(studentobj.usn,courseobj.courseCode)
return HttpResponse(resp)
else:
studentlist=student.objects.all()
courselist=course.objects.all()
return render(request,'register.html',{'student_list':studentlist,'course_list':courselist})
def enrolledStudents(request):
if request.method=="POST":
cid=request.POST.get("course")
courseobj=course.objects.get(id=cid)
studentlistobj=courseobj.student_set.all()
return render(request,'enrolledlist.html',{'course':courseobj,'student_list':studentlistobj})
else:
courselist=course.objects.all()
return render(request,'enrolledlist.html',{'Course_List':courselist})
def add_project(request):
if request.method=="POST":
form=projectForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse("<h1>Project Data Successfully saved</h1>")
else:
return HttpResponse("<h1>Project details not saved</h1>")
else:
form=projectForm()
return render(request, "projectReg.html",{'form':form})
urls.py
from django.contrib import admin
from django.urls import path
from studCourseRegApp.views import enrolledStudentsUsingAjax, generateCSV, home,
registerAjax,
studentlist,courselist,register,enrolledStudents,add_project,StudentListView,StudentDetailVie
w,generatePDF
urlpatterns = [
path('secretadmin/', admin.site.urls),
path('',home),
path('home/',home),
path('studentlist/',studentlist),
path('courselist/',courselist),
path('register/',register),
path('enrolledlist/',enrolledStudents),
path('addproject/',add_project),
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'studCourseRegApp',
]
OUTPUT
PROGRAM 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.
basicTemplate.html
<!DOCTYPE html>
<html>
<head>
<style>
nav{background-color: lightblue;padding: 15px; }
nav a {
color: #fff; /* Text color */
text-decoration: none; /* Remove underline */
padding: 10px 20px; /* Padding around each link */
margin: 0px 10px; /* Spacing between links */
border-radius: 5px; /* Rounded corners */
background-color: #555;
flex-wrap: wrap;
nav a:hover {
background-color:aqua;/* Background color on hover */
}
ul {
list-style: none;
margin: 0;
padding: 0;
display: flex; /* Use flexbox */
flex-wrap: wrap; /* Allow items to wrap to the next line */
</style>
<title>
{% block title %} {% endblock %}
</title>
</head>
<body>
<center> <h1 style="background-color: blue;color:yellow"> STUDENT COURSE
REGISTRATION PORTAL</h1></center>
<nav>
<ul>
<li> <a href="/home/">HOME</a></li>
<li> <a href="/studentlist/">STUDENT LIST</a></li>
<li> <a href="/courselist/">COURSE LIST</a> </li>
<li> <a href="/register/">REGISTER</a></li>
<li> <a href="/enrolledlist/">ENROLLED LIST</a></li>
<li> <a href="/addproject/">ADD PROJECT</a></li>
<li><a href="/genericlistviewstudent/">GENERIC STUDENT LIST VIEW</a></li>
<li> <a href="/download_course_table_as_csv/">DOWNLOAD COURSE AS
CSV</a> </li>
<li> <a href="/download_course_table_as_pdf/">DWONLOAD COURSE AS
PDF</a></li>
</ul>
</nav>
<section>
{% block content %} {% endblock %}
</section>
<footer>
<hr/>
<center>
© Designed and Developeb by Dr. Harish Kumar B T, Dept. of CSE, BIT,
Bangalore-04
</center>
</footer>
</body>
</html>
home.html
{% extends 'basicTemplate.html' %}
{% block title %} Home Page {% endblock %}
{% block content %}
{% endblock %}
studentlist.html
{% extends 'basicTemplate.html' %}
{% block title %} Student List {% endblock %}
{% block content%}
<h1>Student List</h1>
<table border="1">
<tr>
<th>
USN
</th>
<th>
NAME
</th>
<th>
SEM
</th>
</tr>
{% for s in student_list %}
<tr>
<td>{{s.usn}}</td>
<td>{{s.name}}</td>
<td>{{s.sem}}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
courselist.html
{% extends 'basicTemplate.html' %}
{% block title %} Course List {% endblock %}
{% block content%}
<h1> Course List</h1>
<table border="1">
<tr>
<th>
Sub Code
</th>
<th>
Sub Name
</th>
<th>
Credits
</th>
</tr>
{% for c in course_list %}
<tr>
<td>{{c.courseCode}}</td>
<td>{{c.courseName}}</td>
<td>{{c.courseCredits}}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
enrolledlist.html
{% extends 'basicTemplate.html' %}
{% block title %} Course Registration Details {% endblock %}
{% block content %}
{% if student_list %}
<h1> List of Students registered of the course {{course.courseCode}}</h1>
<table border="1">
<tr>
<th>
USN
</th>
<th>
NAME
</th>
<th>
SEM
</th>
</tr>
{% for s in student_list %}
<tr>
<td>{{s.usn}}</td>
<td>{{s.name}}</td>
<td>{{s.sem}}</td>
</tr>
{% endfor %}
</table>
{% endif %}
</form>
{% endblock %}
register.html
{% extends 'basicTemplate.html' %}
{% block title %} Course Register Page {% endblock %}
{% block content %}
Select Course:
<select name="course">
{% for c in course_list %}
<option value="{{c.id}}">{{c.courseCode}}</option>
{% endfor %}
</select>
<input type="submit" value="ENROLL"/>
</form>
{% endblock %}
GenericListViewStudent.html
{% extends 'basicTemplate.html' %}
{% block title %} Generic Student List View {% endblock %}
{% block content %}
{% if student_list %}
<table border="1">
<tr>
<th>USN</th>
<th>Courses Enrolled</th>
</tr>
<td>
<a href="/genericdetailedviewstudent/{{student.pk}}">{{student.usn}}</a>
</td>
<td>
{% for course in student.courses.all %}
<span>{{course.courseName}}</span>
{% endfor %}
</td>
</tr>
{% endfor %}
</table>
{% else %}
<h1>No Students Enrolled</h1>
{% endif %}
{% endblock %}
GenericDetailedViewStudent.html
{% extends 'basicTemplate.html' %}
{% block title %} Detailed Student View {% endblock %}
{% block content %}
{% endblock %}
models.py
from django.db import models
from django.forms import ModelForm
class course(models.Model):
courseCode=models.CharField(max_length=10)
courseName=models.CharField(max_length=50)
courseCredits=models.IntegerField()
def __str__(self):
return self.courseCode+" "+self.courseName+" "+str(self.courseCredits)
class student(models.Model):
usn=models.CharField(max_length=10)
name=models.CharField(max_length=40)
sem=models.IntegerField()
courses=models.ManyToManyField(course,related_name='student_set')
def __str__(self):
return self.usn+" "+self.name+" "+str(self.sem)
class projectReg(models.Model):
student=models.ForeignKey(student,on_delete=models.CASCADE)
ptitle=models.CharField(max_length=30)
planguage=models.CharField(max_length=30)
pduration=models.IntegerField()
class projectForm(ModelForm):
required_css_class="required"
class Meta:
model=projectReg
fields=['student','ptitle','planguage','pduration']
views.py
from django.http import HttpResponse
def studentlist(request):
s=student.objects.all()
return render(request,'studentlist.html',{'student_list':s})
def courselist(request):
c=course.objects.all()
return render(request,'courselist.html',{'course_list':c})
def register(request):
if request.method=="POST":
sid=request.POST.get("student")
cid=request.POST.get("course")
studentobj=student.objects.get(id=sid)
courseobj=course.objects.get(id=cid)
res=studentobj.courses.filter(id=cid)
if res:
resp="<h1>Student with usn %s has already enrolled for the
%s<h1>"%(studentobj.usn,courseobj.courseCode)
return HttpResponse(resp)
studentobj.courses.add(courseobj)
resp="<h1>student with usn %s successfully enrolled for the course with sub code
%s</h1>"%(studentobj.usn,courseobj.courseCode)
return HttpResponse(resp)
else:
studentlist=student.objects.all()
courselist=course.objects.all()
return render(request,'register.html',{'student_list':studentlist,'course_list':courselist})
def enrolledStudents(request):
if request.method=="POST":
cid=request.POST.get("course")
courseobj=course.objects.get(id=cid)
studentlistobj=courseobj.student_set.all()
return render(request,'enrolledlist.html',{'course':courseobj,'student_list':studentlistobj})
else:
courselist=course.objects.all()
return render(request,'enrolledlist.html',{'Course_List':courselist})
def add_project(request):
if request.method=="POST":
form=projectForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse("<h1>Project Data Successfully saved</h1>")
else:
return HttpResponse("<h1>Project details not saved</h1>")
else:
form=projectForm()
return render(request, "projectReg.html",{'form':form})
class StudentDetailView(generic.DetailView):
model=student
template_name="GenericDetailedViewStudent.html"
urls.py
from django.contrib import admin
from django.urls import path
from studCourseRegApp.views import enrolledStudentsUsingAjax, generateCSV, home,
registerAjax,
studentlist,courselist,register,enrolledStudents,add_project,StudentListView,StudentDetailVie
w
urlpatterns = [
path('secretadmin/', admin.site.urls),
path('',home),
path('home/',home),
path('studentlist/',studentlist),
path('courselist/',courselist),
path('register/',register),
path('enrolledlist/',enrolledStudents),
path('addproject/',add_project),
path('genericlistviewstudent/',StudentListView.as_view()),
path('genericdetailedviewstudent/<int:pk>/',StudentDetailView.as_view()),
]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'studCourseRegApp',
]
OUTPUT
4.2 . Develop example Django app that performs CSV and PDF generation for any models
created in previous laboratory component.
basicTemplate.html
<!DOCTYPE html>
<html>
<head>
<style>
nav{background-color: lightblue;padding: 15px; }
nav a {
color: #fff; /* Text color */
text-decoration: none; /* Remove underline */
padding: 10px 20px; /* Padding around each link */
margin: 0px 10px; /* Spacing between links */
border-radius: 5px; /* Rounded corners */
background-color: #555;
flex-wrap: wrap;
nav a:hover {
background-color:aqua;/* Background color on hover */
}
ul {
list-style: none;
margin: 0;
padding: 0;
display: flex; /* Use flexbox */
flex-wrap: wrap; /* Allow items to wrap to the next line */
flex-direction: row; /* Display items in a column */
}
li {
margin-right: 20px;
margin-bottom: 25px;
}
</style>
<title>
{% block title %} {% endblock %}
</title>
</head>
<body>
<center> <h1 style="background-color: blue;color:yellow"> STUDENT COURSE
REGISTRATION PORTAL</h1></center>
<nav>
<ul>
<li> <a href="/home/">HOME</a></li>
<li> <a href="/studentlist/">STUDENT LIST</a></li>
<li> <a href="/courselist/">COURSE LIST</a> </li>
<li> <a href="/register/">REGISTER</a></li>
<li> <a href="/enrolledlist/">ENROLLED LIST</a></li>
<li> <a href="/addproject/">ADD PROJECT</a></li>
<li><a href="/genericlistviewstudent/">GENERIC STUDENT LIST VIEW</a></li>
<li> <a href="/download_course_table_as_csv/">DOWNLOAD COURSE AS
CSV</a> </li>
<li> <a href="/download_course_table_as_pdf/">DWONLOAD COURSE AS
PDF</a></li>
</ul>
</nav>
<section>
{% block content %} {% endblock %}
</section>
<footer>
<hr/>
<center>
© Designed and Developeb by Dr. Harish Kumar B T, Dept. of CSE, BIT,
Bangalore-04
</center>
</footer>
</body>
</html>
models.py
from django.db import models
from django.forms import ModelForm
class course(models.Model):
courseCode=models.CharField(max_length=10)
courseName=models.CharField(max_length=50)
courseCredits=models.IntegerField()
def __str__(self):
return self.courseCode+" "+self.courseName+" "+str(self.courseCredits)
class student(models.Model):
usn=models.CharField(max_length=10)
name=models.CharField(max_length=40)
sem=models.IntegerField()
courses=models.ManyToManyField(course,related_name='student_set')
def __str__(self):
return self.usn+" "+self.name+" "+str(self.sem)
class projectReg(models.Model):
student=models.ForeignKey(student,on_delete=models.CASCADE)
ptitle=models.CharField(max_length=30)
planguage=models.CharField(max_length=30)
pduration=models.IntegerField()
class projectForm(ModelForm):
required_css_class="required"
class Meta:
model=projectReg
fields=['student','ptitle','planguage','pduration']
views.py
from django.http import HttpResponse
from django.shortcuts import render
from studCourseRegApp.models import student,course, projectForm
def studentlist(request):
s=student.objects.all()
return render(request,'studentlist.html',{'student_list':s})
def courselist(request):
c=course.objects.all()
return render(request,'courselist.html',{'course_list':c})
def register(request):
if request.method=="POST":
sid=request.POST.get("student")
cid=request.POST.get("course")
studentobj=student.objects.get(id=sid)
courseobj=course.objects.get(id=cid)
res=studentobj.courses.filter(id=cid)
if res:
resp="<h1>Student with usn %s has already enrolled for the
%s<h1>"%(studentobj.usn,courseobj.courseCode)
return HttpResponse(resp)
studentobj.courses.add(courseobj)
resp="<h1>student with usn %s successfully enrolled for the course with sub code
%s</h1>"%(studentobj.usn,courseobj.courseCode)
return HttpResponse(resp)
else:
studentlist=student.objects.all()
courselist=course.objects.all()
return render(request,'register.html',{'student_list':studentlist,'course_list':courselist})
def enrolledStudents(request):
if request.method=="POST":
cid=request.POST.get("course")
courseobj=course.objects.get(id=cid)
studentlistobj=courseobj.student_set.all()
return render(request,'enrolledlist.html',{'course':courseobj,'student_list':studentlistobj})
else:
courselist=course.objects.all()
return render(request,'enrolledlist.html',{'Course_List':courselist})
def add_project(request):
if request.method=="POST":
form=projectForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse("<h1>Project Data Successfully saved</h1>")
else:
return HttpResponse("<h1>Project details not saved</h1>")
else:
form=projectForm()
return render(request, "projectReg.html",{'form':form})
class StudentDetailView(generic.DetailView):
model=student
template_name="GenericDetailedViewStudent.html"
import csv
def generateCSV(request):
courses=course.objects.all()
resp=HttpResponse(content_type="text/csv")
resp['Content-Disposition']='attachment; filename=course_data.csv'
writer=csv.writer(resp)
writer.writerow(['Course Code','Course Name','Course Credits'])
for c in courses:
writer.writerow([c.courseCode,c.courseName,c.courseCredits])
return resp
for c in courses:
table_data.append([c.courseCode,c.courseName,str(c.courseCredits)])
table=Table(table_data)
pdf.build([table])
return resp
urls.py
from django.contrib import admin
from django.urls import path
from studCourseRegApp.views import enrolledStudentsUsingAjax, generateCSV, home,
registerAjax,
studentlist,courselist,register,enrolledStudents,add_project,StudentListView,StudentDetailVie
w,generatePDF
urlpatterns = [
path('secretadmin/', admin.site.urls),
path('',home),
path('home/',home),
path('studentlist/',studentlist),
path('courselist/',courselist),
path('register/',register),
path('enrolledlist/',enrolledStudents),
path('addproject/',add_project),
path('genericlistviewstudent/',StudentListView.as_view()),
path('genericdetailedviewstudent/<int:pk>/',StudentDetailView.as_view()),
path('download_course_table_as_csv/',generateCSV),
path('download_course_table_as_pdf/',generatePDF),
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'studCourseRegApp',
]
OUTPUT
PROGRAM 5
5.1 . Develop a registration page for student enrolment as done in Module 2 but without page
refresh using AJAX.
basicTemplate.html
<!DOCTYPE html>
<html>
<head>
<style>
nav{background-color: lightblue;padding: 15px; }
nav a {
color: #fff; /* Text color */
text-decoration: none; /* Remove underline */
padding: 10px 20px; /* Padding around each link */
margin: 0px 10px; /* Spacing between links */
border-radius: 5px; /* Rounded corners */
background-color: #555;
flex-wrap: wrap;
nav a:hover {
background-color:aqua;/* Background color on hover */
}
ul {
list-style: none;
margin: 0;
padding: 0;
display: flex; /* Use flexbox */
flex-wrap: wrap; /* Allow items to wrap to the next line */
flex-direction: row; /* Display items in a column */
}
li {
margin-right: 20px;
margin-bottom: 25px;
</style>
<title>
{% block title %} {% endblock %}
</title>
</head>
<body>
<center> <h1 style="background-color: blue;color:yellow"> STUDENT COURSE
REGISTRATION PORTAL</h1></center>
<nav>
<ul>
<li> <a href="/home/">HOME</a></li>
<li> <a href="/studentlist/">STUDENT LIST</a></li>
<li> <a href="/courselist/">COURSE LIST</a> </li>
<li> <a href="/register/">REGISTER</a></li>
<li> <a href="/enrolledlist/">ENROLLED LIST</a></li>
<li> <a href="/addproject/">ADD PROJECT</a></li>
<li><a href="/genericlistviewstudent/">GENERIC STUDENT LIST VIEW</a></li>
<li> <a href="/download_course_table_as_csv/">DOWNLOAD COURSE AS
CSV</a> </li>
<li> <a href="/download_course_table_as_pdf/">DWONLOAD COURSE AS
PDF</a></li>
</ul>
</nav>
<section>
{% block content %} {% endblock %}
</section>
<footer>
<hr/>
<center>
© Designed and Developeb by Dr. Harish Kumar B T, Dept. of CSE, BIT,
Bangalore-04
</center>
</footer>
</body>
</html>
models.py
from django.db import models
from django.forms import ModelForm
class course(models.Model):
courseCode=models.CharField(max_length=10)
courseName=models.CharField(max_length=50)
courseCredits=models.IntegerField()
def __str__(self):
return self.courseCode+" "+self.courseName+" "+str(self.courseCredits)
class student(models.Model):
usn=models.CharField(max_length=10)
name=models.CharField(max_length=40)
sem=models.IntegerField()
courses=models.ManyToManyField(course,related_name='student_set')
def __str__(self):
return self.usn+" "+self.name+" "+str(self.sem)
class projectReg(models.Model):
student=models.ForeignKey(student,on_delete=models.CASCADE)
ptitle=models.CharField(max_length=30)
planguage=models.CharField(max_length=30)
pduration=models.IntegerField()
class projectForm(ModelForm):
required_css_class="required"
class Meta:
model=projectReg
fields=['student','ptitle','planguage','pduration']
views.py
from django.http import HttpResponse
from django.shortcuts import render
from studCourseRegApp.models import student,course, projectForm
def studentlist(request):
s=student.objects.all()
return render(request,'studentlist.html',{'student_list':s})
def courselist(request):
c=course.objects.all()
return render(request,'courselist.html',{'course_list':c})
def register(request):
if request.method=="POST":
sid=request.POST.get("student")
cid=request.POST.get("course")
studentobj=student.objects.get(id=sid)
courseobj=course.objects.get(id=cid)
res=studentobj.courses.filter(id=cid)
if res:
resp="<h1>Student with usn %s has already enrolled for the
%s<h1>"%(studentobj.usn,courseobj.courseCode)
return HttpResponse(resp)
studentobj.courses.add(courseobj)
resp="<h1>student with usn %s successfully enrolled for the course with sub code
%s</h1>"%(studentobj.usn,courseobj.courseCode)
return HttpResponse(resp)
else:
studentlist=student.objects.all()
courselist=course.objects.all()
return render(request,'register.html',{'student_list':studentlist,'course_list':courselist})
def enrolledStudents(request):
if request.method=="POST":
cid=request.POST.get("course")
courseobj=course.objects.get(id=cid)
studentlistobj=courseobj.student_set.all()
return render(request,'enrolledlist.html',{'course':courseobj,'student_list':studentlistobj})
else:
courselist=course.objects.all()
return render(request,'enrolledlist.html',{'Course_List':courselist})
def add_project(request):
if request.method=="POST":
form=projectForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse("<h1>Project Data Successfully saved</h1>")
else:
class StudentDetailView(generic.DetailView):
model=student
template_name="GenericDetailedViewStudent.html"
import csv
def generateCSV(request):
courses=course.objects.all()
resp=HttpResponse(content_type="text/csv")
resp['Content-Disposition']='attachment; filename=course_data.csv'
writer=csv.writer(resp)
writer.writerow(['Course Code','Course Name','Course Credits'])
for c in courses:
writer.writerow([c.courseCode,c.courseName,c.courseCredits])
return resp
urls.py
from django.contrib import admin
from django.urls import path
from studCourseRegApp.views import enrolledStudentsUsingAjax, generateCSV, home,
registerAjax,
studentlist,courselist,register,enrolledStudents,add_project,StudentListView,StudentDetailVie
w,generatePDF
urlpatterns = [
path('secretadmin/', admin.site.urls),
path('',home),
path('home/',home),
path('studentlist/',studentlist),
path('courselist/',courselist),
path('register/',register),
path('enrolledlist/',enrolledStudents),
path('addproject/',add_project),
path('genericlistviewstudent/',StudentListView.as_view()),
path('genericdetailedviewstudent/<int:pk>/',StudentDetailView.as_view()),
path('download_course_table_as_csv/',generateCSV),
path('download_course_table_as_pdf/',generatePDF),
path('courseRegUsingAjax/',registerAjax),
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'studCourseRegApp',
]
OUTPUT
5.2 . Develop a search application in Django using AJAX that displays courses enrolled by a
student being searched.
basicTemplate.html
<!DOCTYPE html>
<html>
<head>
<style>
nav{background-color: lightblue;padding: 15px; }
nav a {
color: #fff; /* Text color */
text-decoration: none; /* Remove underline */
padding: 10px 20px; /* Padding around each link */
margin: 0px 10px; /* Spacing between links */
border-radius: 5px; /* Rounded corners */
background-color: #555;
flex-wrap: wrap;
nav a:hover {
background-color:aqua;/* Background color on hover */
}
ul {
list-style: none;
margin: 0;
padding: 0;
display: flex; /* Use flexbox */
flex-wrap: wrap; /* Allow items to wrap to the next line */
flex-direction: row; /* Display items in a column */
}
li {
margin-right: 20px;
margin-bottom: 25px;
</style>
<title>
{% block title %} {% endblock %}
</title>
</head>
<body>
<center> <h1 style="background-color: blue;color:yellow"> STUDENT COURSE
REGISTRATION PORTAL</h1></center>
<nav>
<ul>
<li> <a href="/home/">HOME</a></li>
<li> <a href="/studentlist/">STUDENT LIST</a></li>
<li> <a href="/courselist/">COURSE LIST</a> </li>
<li> <a href="/register/">REGISTER</a></li>
<li> <a href="/enrolledlist/">ENROLLED LIST</a></li>
<li> <a href="/addproject/">ADD PROJECT</a></li>
<li><a href="/genericlistviewstudent/">GENERIC STUDENT LIST VIEW</a></li>
<li> <a href="/download_course_table_as_csv/">DOWNLOAD COURSE AS
CSV</a> </li>
<li> <a href="/download_course_table_as_pdf/">DWONLOAD COURSE AS
PDF</a></li>
</ul>
</nav>
<section>
{% block content %} {% endblock %}
</section>
<footer>
<hr/>
<center>
© Designed and Developeb by Dr. Harish Kumar B T, Dept. of CSE, BIT,
Bangalore-04
</center>
</footer>
</body>
</html>
models.py
from django.db import models
from django.forms import ModelForm
class course(models.Model):
courseCode=models.CharField(max_length=10)
courseName=models.CharField(max_length=50)
courseCredits=models.IntegerField()
def __str__(self):
return self.courseCode+" "+self.courseName+" "+str(self.courseCredits)
class student(models.Model):
usn=models.CharField(max_length=10)
name=models.CharField(max_length=40)
sem=models.IntegerField()
courses=models.ManyToManyField(course,related_name='student_set')
def __str__(self):
return self.usn+" "+self.name+" "+str(self.sem)
class projectReg(models.Model):
student=models.ForeignKey(student,on_delete=models.CASCADE)
ptitle=models.CharField(max_length=30)
planguage=models.CharField(max_length=30)
pduration=models.IntegerField()
class projectForm(ModelForm):
required_css_class="required"
class Meta:
model=projectReg
fields=['student','ptitle','planguage','pduration']
views.py
from django.http import HttpResponse
from django.shortcuts import render
from studCourseRegApp.models import student,course, projectForm
def studentlist(request):
s=student.objects.all()
return render(request,'studentlist.html',{'student_list':s})
def courselist(request):
c=course.objects.all()
return render(request,'courselist.html',{'course_list':c})
def register(request):
if request.method=="POST":
sid=request.POST.get("student")
cid=request.POST.get("course")
studentobj=student.objects.get(id=sid)
courseobj=course.objects.get(id=cid)
res=studentobj.courses.filter(id=cid)
if res:
resp="<h1>Student with usn %s has already enrolled for the
%s<h1>"%(studentobj.usn,courseobj.courseCode)
return HttpResponse(resp)
studentobj.courses.add(courseobj)
resp="<h1>student with usn %s successfully enrolled for the course with sub code
%s</h1>"%(studentobj.usn,courseobj.courseCode)
return HttpResponse(resp)
else:
studentlist=student.objects.all()
courselist=course.objects.all()
return render(request,'register.html',{'student_list':studentlist,'course_list':courselist})
def enrolledStudents(request):
if request.method=="POST":
cid=request.POST.get("course")
courseobj=course.objects.get(id=cid)
studentlistobj=courseobj.student_set.all()
return render(request,'enrolledlist.html',{'course':courseobj,'student_list':studentlistobj})
else:
courselist=course.objects.all()
return render(request,'enrolledlist.html',{'Course_List':courselist})
def add_project(request):
if request.method=="POST":
form=projectForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse("<h1>Project Data Successfully saved</h1>")
else:
class StudentDetailView(generic.DetailView):
model=student
template_name="GenericDetailedViewStudent.html"
import csv
def generateCSV(request):
courses=course.objects.all()
resp=HttpResponse(content_type="text/csv")
resp['Content-Disposition']='attachment; filename=course_data.csv'
writer=csv.writer(resp)
writer.writerow(['Course Code','Course Name','Course Credits'])
for c in courses:
writer.writerow([c.courseCode,c.courseName,c.courseCredits])
return resp
urls.py
from django.contrib import admin
from django.urls import path
from studCourseRegApp.views import enrolledStudentsUsingAjax, generateCSV, home,
registerAjax,
studentlist,courselist,register,enrolledStudents,add_project,StudentListView,StudentDetailVie
w,generatePDF
urlpatterns = [
path('secretadmin/', admin.site.urls),
path('',home),
path('home/',home),
path('studentlist/',studentlist),
path('courselist/',courselist),
path('register/',register),
path('enrolledlist/',enrolledStudents),
path('addproject/',add_project),
path('genericlistviewstudent/',StudentListView.as_view()),
path('genericdetailedviewstudent/<int:pk>/',StudentDetailView.as_view()),
path('download_course_table_as_csv/',generateCSV),
path('download_course_table_as_pdf/',generatePDF),
path('courseRegUsingAjax/',registerAjax),
path('course_search_ajax/',enrolledStudentsUsingAjax),
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'studCourseRegApp',
]
OUTPUT