0% found this document useful (0 votes)
75 views38 pages

FSD Lab Manual 2024

Uploaded by

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

FSD Lab Manual 2024

Uploaded by

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

||JAI SRI GURUDEV||

S J C INSTITUTE OF TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

FULLSTACK DEVELOPMENT
INTEGRATED LAB MANUAL [21CSL62]
(VI SEM CBCS, 2021 SCHEME)

Prepared By
Gavina CG & Kiran Kumar PN
Assistant Professor
Dept. of CSE

S.J.C.INSTITUTEOF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
CHICKBALLAPUR -562101
During the Year: 2024
Teaching Learning Plan
Content
Exp. List of Programs
No.
PYTHON SETUP AND DJANGO INSTALLATION
1. Develop a Django app that displays current date and time in server.
2. 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.
3. Develop a simple Django app that displays an unordered list of fruits and ordered list of
selected students for an event
4. 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.
5. 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.
6. For student and course models created in Lab experiment for Module2, register admin
interfaces, perform migrations and illustrate data entry through admin forms.
7. Develop a Model form for student that contains his topic chosen for project, languages
used and duration with a model called project.
8. 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.
9. Develop example Django app that performs CSV and PDF generation for any models
created in previous laboratory component.
10. Develop a registration page for student enrolment as done in Module 2 but without page
refresh using AJAX.
11. Develop a search application in Django using AJAX that displays courses enrolled by a
student being searched.
FSD Laboratory 2024

Module-1:MVCbasedWebDesigning
LaboratoryComponent:
1. InstallationofPython,DjangoandVisualStudiocodeeditorscanbedemonstra
ted.

PythondownloadandinstallationLink:https://www.python
.org/downloads/
VisualStudioCodedownloadandinstallationlink:https://co
de.visualstudio.com/
Djangoinstallation:
Openacommandpromptandtypefollowingcommand:pipinstalldjan
go

2. Creationofvirtualenvironment,DjangoprojectandAppshouldbedemonst
rated
Followthesesteps
1. Install thePython extension.- Open VS Code IDE and click extensions
thereautomaticallyuwillbeshownPythonextension(MakesureyouareconnectedtoI
nternet)
2. Onyourfilesystem,createaprojectfolder
3. Inthatfolder,usethefollowingcommand(asappropriatetoyourcomputer)tocreateavirtu
alenvironmentnamedenvbasedonyourcurrentinterpreter:
#Windows
python-mvenvenv

4. OpentheprojectfolderinVSCodebyrunningcode.,orbyrunningVSCode
andusingtheFile>OpenFoldercommand.
5. InVSCode,opentheCommandPalette(View>CommandPaletteor(Ctrl+Shift+P
)).ThenselectthePython:SelectInterpretercommand:

6. The command presents a list of available interpreters that VS Code can


locateautomatically(yourlistwillvary;ifyoudon'tseethedesiredinterpreter,seeConfiguri

Dept. of CSE Page 4


FSD Laboratory 2024

ngPythonenvironments).Fromthelist,selectthevirtualenvironmentinyourprojectfoldert
hatstartswith./envor.\env:
7. CreateaNewTerminal:InMenuTerminal->NewTerminaloption

Creatingproject:
1. Createadjangoproject-

Typefollowingcommandintheterminalopened:django-
admin startprojectp.

(dotfollowingprojectnameisimportantwhichreferstocurrentdirectory)

This startprojectcommandassumes(byuseof
.attheend)thatthecurrentfolderisyourprojectfolder,andcreatesthefollowingwithinit:
● manage.py:TheDjangocommand-
lineadministrativeutilityfortheproject.Yourunadministrativecommandsfortheproj
ectusingpythonmanage.py
<command>[options].
● A subfolder namedpwhichcontainsthe following files:
o init.py:anemptyfilethattellsPythonthatthisfolderisaPythonpackage.
o wsgi.py:anentrypointforWSGI-compatiblewebserverstoserveyourproject.
You typically leave this file as-is as it provides the hooks
forproductionwebservers.
o settings.py: contains settings for Django project, which you modify
inthecourseofdevelopingawebapp.
o urls.py: contains a table of contents for the Django project, which
youalsomodifyinthecourseofdevelopment.

2. ToverifytheDjangoproject,makesureyourvirtualenvironmentisactivated,thenstartDjan
go'sdevelopmentserverusingthe
commandpython manage.py runserver. The server runs on the defaultport 8000,
and you see output like the following output in the terminalwindow:
Verifyserver bytyping:
pythonmanage.pyrunserver

Dept. of CSE Page 5


FSD Laboratory 2024

When you run the server the first time, it creates a default SQLite database inthe
filedb.sqlite3, which is intended for development purposes but can be usedin production for
low-volume web apps. Also, Django's built-in web server
isintendedonlyforlocaldevelopmentpurposes.Whenyoudeploytoawebhost,however,
Django uses the host's web server instead. The wsgi.pymodule in theDjango project
takescareof hooking intothe production servers.
Ifyouwanttouseadifferentportthanthedefault8000,specifytheportnumberonthecommandline,s
uchaspythonmanage.pyrunserver5000.
3. When you're done, close the browser window and stop the server in
VSCodeusingCtrl+Casindicatedintheterminaloutputwindow.
4. IntheVSCodeTerminalwithyourvirtualenvironmentactivated,runtheadministrativ
eutility'sstartappcommandin your project folder(wheremanage.pyresides):

pythonmanage.pystartapplab1

5. Thecommand createsafolder calledlab1that containsanumberofcode


filesandonesubfolder.Ofthese,youfrequentlyworkwithviews.py(thatcontains the
functions that define pages in your web app)and models.py(that
containsclasses defining your data objects).The migrationsfolder is used by
Django's administrative utility to managedatabase versions. There arealso the files
apps.py(appconfiguration), admin.py(for creating an administrative
interface),andtests.py(forunittests).

Dept. of CSE Page 6


FSD Laboratory 2024

1. Develop a Django app that displays current date and time in server

Views.py in app
fromdjango.shortcutsimportrender
fromdjango.httpimportHttpResponse

importdatetime
defcurrent_datetime(request):
dt=datetime.datetime.now()
resp="<h1>Current date and time is %s</h1>"%(dt)
returnHttpResponse(resp)

urls.py in project
fromdjango.contrib import admin
fromdjango.urls import path
fromap1.viewsimportcurrent_datetime

urlpatterns= [
path('admin/', admin.site.urls),
path('cdt/', current_datetime),

Output:

Dept. of CSE Page 7


FSD Laboratory 2024

2. 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 in app
fromdjango.shortcutsimportrender
fromdjango.httpimportHttpResponse
importdatetime
defcurrent_datetime(request):
dt=datetime.datetime.now()
resp="<h1>It is now %s.</h1>"%(dt)
returnHttpResponse(resp)

deffour_hours_ahead(request):
dt=datetime.datetime.now() +datetime.timedelta(hours=4)
resp="<h1>After 4hour(s), it will be %s.</h1>"%(dt)
returnHttpResponse(resp)

deffour_hours_before(request):
dt=datetime.datetime.now() +datetime.timedelta(hours=-4)
resp="<h1>Before 4 hour(s), it was %s.</h1>"%(dt)
returnHttpResponse(resp)

urls.py in project
fromdjango.contrib import admin
fromdjango.urls import path
fromap1.viewsimportcurrent_datetime,four_hours_ahead, four_hours_before

urlpatterns= [
path('admin/', admin.site.urls),
path('cdt/', current_datetime),
path('fhrsa/',four_hours_ahead),
path('fhrsb/',four_hours_before),

Output:

Dept. of CSE Page 8


FSD Laboratory 2024

Module-2

3. Develop a simple Django app that displays an unordered list of fruits and ordered list
of selected students for an event

Views.py in app name members


fromdjango.shortcutsimportrender
fromdjango.httpimportHttpResponse
fromdjango.templateimportloader

defshowlist(request):
template=loader.get_template('showlist.html')
fruits=["Mango","Apple","Bananan","Jackfruits"]
student_names=["Tony","Mony","Sony","Bob"]
returnrender(request,'showlist.html',{"fruits":fruits,"student_names":student_names}
)

URLS.py in app name members


fromdjango.urlsimportpath
from .importviews

urlpatterns= [
path('showlist/', views.showlist, name='showlist'),

URLS.py in project name store


fromdjango.contribimportadmin
fromdjango.urlsimportpath , include

frommembers.viewsimportshowlist
urlpatterns= [
path('admin/', admin.site.urls),
path('', include('members.urls')),
]

Create templatesfolder in app:


showlist.html file in templates folder
<html>
<styletype="text/css">
#i1 {background-color: lightgreen;color:brown;display:table}
#i2 {background-color: black;color:yellow}
</style>
<body>
<h1id="i1">Unordered list of fruits</h1>
<ul>

Dept. of CSE Page 9


FSD Laboratory 2024

{% for fruit in fruits %}


<li>{{ fruit }}</li>
{% endfor %}
</ul>
<h1id="i2">Ordered list of Students</h1>
<ol>
{% for student in student_names %}
<li>{{ student }}</li>
{% endfor %}
</ol>
</body>
</html>

Setting.py( make sure that ur app name should be added to installed app)
INSTALLED_APPS= [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'members'
]

Output:

Dept. of CSE Page 10


FSD Laboratory 2024

4. 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.

Views.py in app3
fromdjango.httpimportHttpResponse
fromdjango.shortcutsimportrender
fromdjango.templateimportContext, Template
defhome(request):
returnrender(request,'home.html')

defaboutus(request):
returnrender(request,'aboutus.html')

defcontactus(request):
returnrender(request,'contactus.html')

URLS.py in app3
fromdjango.urlsimportpath

from .importviews

urlpatterns= [
# path('admin/', admin.site.urls),

path('aboutus/', views.aboutus,name='aboutus'),
path('home/', views.home,name='home'),
path('contactus/',views.contactus,name='contactu'),

URLS.py in proj
fromdjango.contribimportadmin
fromdjango.urlsimportpath,include

urlpatterns= [

path('admin/', admin.site.urls),
path('',include('app1.urls')),
path('',include('app2.urls')),
path('',include('app3.urls')),

Dept. of CSE Page 11


FSD Laboratory 2024

Create templatesfolder in app:


layout.html file in templates folder
<html>
<title>{% block title %} {% endblock %} </title>
<styletype="text/css">
nav {background-color: lightblue;padding:10px}
</style>
<body>
<nav>
<ahref="/home/">Home</a>|
<ahref="/aboutus/">About Us</a>|
<ahref="/contactus/">Contact Us</a>|
</nav>
<section>
{% block content %}{% endblock %}
</section>
<footer>
<hr>
&copy; ISE, Developed by ABC, Inc.
</footer>
</body>
</html>

home.html

{% extends 'layout.html' %}
{% block title %} Home
{% endblock %}
{% block content %}
<h2>This is the home page</h2>
{% endblock %}

aboutus.html
{% extends 'layout.html' %}
{% block title %} About Us
{% endblock %}
{% block content %}
<h2>We are DJango developers</h2>
{% endblock %}

contactus.html
{% extends 'layout.html' %}
{% block title %} Contact us
{% endblock %}
{% block content %}
<h2>Out phone: 8147235567 <br> Address: Ram SJCIT</h2>
Dept. of CSE Page 12
FSD Laboratory 2024

{% endblock %}

Setting.py
INSTALLED_APPS= [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app1' ,
'app2' ,
'app3' ,

Output:

Dept. of CSE Page 13


FSD Laboratory 2024

5. 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.

Create templatesfolder in app:

course_search.html file in templates folder

<html>
<body>
<formmethod="POST"action="">
Courses
{% csrf_token %}
<selectname="cname">
{%for course in courses %}
<optionvalue="{{course.id}}">{{course.course_name}}</option>
{% endfor %}
</select>
<inputtype="submit"value="Search">
</form>
</body>
</html>

selected_students.html

<html>
<body>
<tableborder>
<tr>
<th>Student Name</th>
<th>Student USN</th>
<th>Sem</th>
</tr>
{% for student in student_list %}
<tr>
<td>{{student.student_name}}</td>
<td>{{student.student_usn}}</td>
<td>{{student.student_sem}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>

reg.html

Dept. of CSE Page 14


FSD Laboratory 2024

<html>
<body>
<formmethod="post"action="">
{% csrf_token %}
Student Name
<selectname="sname">
{%for student in students %}
<optionvalue="{{student.id}}">{{student.student_name}}</option>
{% endfor %}
</select><br>
Course Name
<selectname="cname">
{%for course in courses %}
<optionvalue="{{course.id}}">{{course.course_name}}</option>
{% endfor %}

</select><br>
<inputtype="submit"value="Enroll">
</form>
</body>
</html>

Views.py in app

fromdjango.httpimportHttpResponse
fromdjango.shortcutsimportrender

fromap1.modelsimportCourse, ProjectReg, Student

defreg(request):
ifrequest.method=="POST":
sid=request.POST.get("sname")
cid=request.POST.get("cname")
student=Student.objects.get(id=sid)
course=Course.objects.get(id=cid)
res=student.enrolment.filter(id=cid)
ifres:
returnHttpResponse("<h1>Student already enrolled</h1>")
student.enrolment.add(course)
returnHttpResponse("<h1>Student enrolled successfully</h1>")

else:
students=Student.objects.all()
courses=Course.objects.all()
returnrender(request,"reg.html",{"students":students, "courses":courses})
defcourse_search(request):
ifrequest.method=="POST":
cid=request.POST.get("cname")

Dept. of CSE Page 15


FSD Laboratory 2024

s=Student.objects.all()
student_list=list()
forstudentins:
ifstudent.enrolment.filter(id=cid):
student_list.append(student)
iflen(student_list)==0:
returnHttpResponse("<h1>No Students enrolled</h1>")
returnrender(request,"selected_students.html",{"student_list":student_list})

else:
courses=Course.objects.all()
returnrender(request,"course_search.html",{"courses":courses})

models.py in app
fromdjango.dbimportmodels
fromdjango.formsimportModelForm

# Create your models here.


classCourse(models.Model):
course_code=models.CharField(max_length=40)
course_name=models.CharField(max_length=100)
course_credits=models.IntegerField()
def__str__(self):
returnself.course_name

classStudent(models.Model):
student_usn=models.CharField(max_length=20)
student_name=models.CharField(max_length=100)
student_sem=models.IntegerField()
enrolment=models.ManyToManyField(Course)
def__str__(self):
returnself.student_name+"("+self.student_usn+")"

urls.py in project

fromdjango.contribimportadmin
fromdjango.urlsimportpath, re_path

fromap1.viewsimportreg,course_search
admin.site.site_header="My Site Header"
admin.site.site_title="My Site Title"
admin.site.index_title="My Site Index"
urlpatterns= [
path('admin/', admin.site.urls),
path('reg/', reg),
path('course_search/', course_search)
]

Dept. of CSE Page 16


FSD Laboratory 2024

Output:

Perform migrations before running:

 python manage.py makemigrations

 pythonmanage.py migrate

 Databaseinput:Insertstudentandcoursesrecordin db.sqlite3 or
PhPmyadmin

Dept. of CSE Page 17


FSD Laboratory 2024

Back End

Dept. of CSE Page 18


FSD Laboratory 2024

Module-3
6. For student and course models created in Lab experiment for Module2, register admin
interfaces, perform migrations and illustrate data entry through admin forms

python manage.py createsuperuser

makefollowingchangestoadmin.py

fromdjango.contribimportadmin

fromap1.modelsimportCourse, Student

# Register your models here.


#admin.site.register(Student)
@admin.register(Student)
classStudentAdmin(admin.ModelAdmin):
list_display= ('student_name','student_usn','student_sem')
ordering=('student_name',)
search_fields= ('student_name',)
admin.site.register(Course)

Views.py in app

fromdjango.httpimportHttpResponse
fromdjango.shortcutsimportrender

fromap1.modelsimportCourse, ProjectReg, Student

defreg(request):
ifrequest.method=="POST":
sid=request.POST.get("sname")

Dept. of CSE Page 19


FSD Laboratory 2024

cid=request.POST.get("cname")
student=Student.objects.get(id=sid)
course=Course.objects.get(id=cid)
res=student.enrolment.filter(id=cid)
ifres:
returnHttpResponse("<h1>Student already enrolled</h1>")
student.enrolment.add(course)
returnHttpResponse("<h1>Student enrolled successfully</h1>")

else:
students=Student.objects.all()
courses=Course.objects.all()
returnrender(request,"reg.html",{"students":students, "courses":courses})

defcourse_search(request):
ifrequest.method=="POST":
cid=request.POST.get("cname")
s=Student.objects.all()
student_list=list()
forstudentins:
ifstudent.enrolment.filter(id=cid):
student_list.append(student)
iflen(student_list)==0:
returnHttpResponse("<h1>No Students enrolled</h1>")
returnrender(request,"selected_students.html",{"student_list":student_list})

else:
courses=Course.objects.all()
returnrender(request,"course_search.html",{"courses":courses})

urls.py in project

fromdjango.contribimportadmin
fromdjango.urlsimportpath, re_path

fromap1.viewsimportreg,add_project ,course_search
admin.site.site_header="My Site Header"
admin.site.site_title="My Site Title"
admin.site.index_title="My Site Index"
urlpatterns= [
path('admin/', admin.site.urls),
path('reg/', reg),
path('add_project/', add_project),
path('course_search/', course_search)
]

Dept. of CSE Page 20


FSD Laboratory 2024

Changesto models.py in app

fromdjango.dbimportmodels
fromdjango.formsimportModelForm

# Create your models here.


classCourse(models.Model):
course_code=models.CharField(max_length=40)
course_name=models.CharField(max_length=100)
course_credits=models.IntegerField()
def__str__(self):
returnself.course_name

classStudent(models.Model):
student_usn=models.CharField(max_length=20)
student_name=models.CharField(max_length=100)
student_sem=models.IntegerField()
enrolment=models.ManyToManyField(Course)
def__str__(self):
returnself.student_name+"("+self.student_usn+")"

Create templatesfolder in app:

course_search.html file in templates folder

<html>
<body>
<formmethod="POST"action="">
Courses
{% csrf_token %}
<selectname="cname">
{%for course in courses %}
<optionvalue="{{course.id}}">{{course.course_name}}</option>
{% endfor %}
</select>
<inputtype="submit"value="Search">
</form>
</body>
</html>

selected_students.html

<html>
<body>
<tableborder>
<tr>
<th>Student Name</th>

Dept. of CSE Page 21


FSD Laboratory 2024

<th>Student USN</th>
<th>Sem</th>
</tr>
{% for student in student_list %}
<tr>
<td>{{student.student_name}}</td>
<td>{{student.student_usn}}</td>
<td>{{student.student_sem}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>

reg.html

<html>
<body>
<formmethod="post"action="">
{% csrf_token %}
Student Name
<selectname="sname">
{%for student in students %}
<optionvalue="{{student.id}}">{{student.student_name}}</option>
{% endfor %}
</select><br>
Course Name
<selectname="cname">
{%for course in courses %}
<optionvalue="{{course.id}}">{{course.course_name}}</option>
{% endfor %}

</select><br>
<inputtype="submit"value="Enroll">
</form>
</body>
</html>

Perform remigrations before

running:python manage.py

makemigrations pythonmanage.py migrate

Dept. of CSE Page 22


FSD Laboratory 2024

Output:

Dept. of CSE Page 23


FSD Laboratory 2024

7. Develop a Model form for student that contains his topic chosen for project, languages
used and duration with a model called project.

models.py in app
fromdjango.dbimportmodels
fromdjango.formsimportModelForm

# Create your models here.

classCourse(models.Model):
course_code=models.CharField(max_length=40)
course_name=models.CharField(max_length=100)
course_credits=models.IntegerField()
def__str__(self):
returnself.course_name

classStudent(models.Model):
student_usn=models.CharField(max_length=20)
student_name=models.CharField(max_length=100)
student_sem=models.IntegerField()
enrolment=models.ManyToManyField(Course)
def__str__(self):
returnself.student_name+"("+self.student_usn+")"

classProject(models.Model):
student=models.ForeignKey(Student,on_delete=models.CASCADE)
ptopic=models.CharField(max_length=200)
plangauges=models.CharField(max_length=200)
pduration=models.IntegerField()

classProjectReg(ModelForm):
required_css_class="required"
classMeta:
model=Project
fields=['student','ptopic','plangauges','pduration']

views.py in app

fromdjango.httpimportHttpResponse
fromdjango.shortcutsimportrender

fromap1.modelsimportCourse, ProjectReg, Student

defadd_project(request):
ifrequest.method=="POST":
form=ProjectReg(request.POST)
ifform.is_valid():
form.save()

Dept. of CSE Page 24


FSD Laboratory 2024

returnHttpResponse("<h1>Record inserted successfully</h1>")


else:
returnHttpResponse("<h1>Record not inserted</h1>")
else:
form=ProjectReg()
returnrender(request,"add_project.html",{"form":form})

Create templatesfolder in app:

add_project.htmlinside templates folder

<html>
<formmethod="post"action="">
{% csrf_token %}
<table>
{{ form.as_table}}
<tr>
<td>
<inputtype="submit"value="Submit">
</td>
</tr>
</table>
</form>
</html>

urls.py in project
fromdjango.contribimportadmin
fromdjango.urlsimportpath, re_path

fromap1.viewsimportreg,add_project ,course_search
admin.site.site_header="My Site Header"
admin.site.site_title="My Site Title"
admin.site.index_title="My Site Index"
urlpatterns= [
path('admin/', admin.site.urls),
path('reg/', reg),
path('add_project/', add_project),
path('course_search/', course_search)
]
Perform remigrations before running:

 python manage.py makemigrations

 pythonmanage.py migrate

Dept. of CSE Page 25


FSD Laboratory 2024

Output:

BackEnd

Dept. of CSE Page 26


FSD Laboratory 2024

Module-4

8.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.

views.py in app
fromdjango.viewsimportgeneric
classStudentListView(generic.ListView):
model=Student
template_name="student_list.html"

classStudentDetailView(generic.DetailView):
model=Student
template_name="student_detail.html"

Create templatesfolder in app:


student_list.htmlinside templatesfolder
<html>
<body>
{% if student_list %}
<tableborder>
<tr>
<th>USN</th>
<th>Courses Enrolled</th>
</tr>
{% for student in student_list %}
<tr>
<td><ahref="/student_detail/{{student.pk}}">{{ student.student_usn }}</a></td>
<td>{% for course in student.enrolment.all %}
<span>{{ course.course_name }}</span>
{% endfor %}
</td>
</tr>
{% endfor %}
</table>
{% else %}
<h1>No Students Enrolled</h1>
{% endif %}
</body>
</html>

Dept. of CSE Page 27


FSD Laboratory 2024

student_detail.html

<h1>Student Name: {{ student.student_name }}</h1>


<h1>Student USN: {{ student.student_usn }}</h1>
<h1>Student Sem: {{ student.student_sem }}</h1>

urls.py in project

fromdjango.contribimportadmin
fromdjango.urlsimportpath, re_path

fromap1.viewsimportreg,add_project ,course_search
fromap1.viewsimportStudentListView, StudentDetailView
admin.site.site_header="My Site Header"
admin.site.site_title="My Site Title"
admin.site.index_title="My Site Index"
urlpatterns= [
path('admin/', admin.site.urls),

path('reg/', reg),
path('add_project/', add_project),
path('course_search/', course_search),
path('student_list/', StudentListView.as_view()),
path('student_detail/<int:pk>/', StudentDetailView.as_view()),
]
Output:

Dept. of CSE Page 28


FSD Laboratory 2024

9. Develop example Django app that performs CSV generation for any models created in
previous laboratory component

views.py in app
fromdjango.httpimportHttpResponse
fromdjango.shortcutsimportrender

importcsv
defconstruct_csv_from_model(request):
courses=Course.objects.all()
response=HttpResponse(content_type="text/csv")
response['Content-Disposition'] ='attachment;filename="courses_data.csv"'
writer=csv.writer(response)
writer.writerow(["Course Name","CourseCode","Credits"])
forcourseincourses:
writer.writerow([course.course_name,course.course_code,course.course_credits])
returnresponse

urls.py in project
fromdjango.contribimportadmin
fromdjango.urlsimportpath, re_path

fromap1.viewsimportreg,add_project ,course_search
fromap1.viewsimportStudentListView, StudentDetailView
fromap1.viewsimportStudentListView,StudentDetailView,construct_csv
fromap1.viewsimportconstruct_csv_from_model

admin.site.site_header="My Site Header"


admin.site.site_title="My Site Title"
admin.site.index_title="My Site Index"
urlpatterns= [
path('admin/', admin.site.urls),
path('reg/', reg),
path('add_project/', add_project),
path('course_search/', course_search),
path('student_list/', StudentListView.as_view()),
path('student_detail/<int:pk>/', StudentDetailView.as_view()),
path('construct_csv/', construct_csv),
path('construct_csv_from_model/', construct_csv_from_model),
]

Dept. of CSE Page 29


FSD Laboratory 2024

Output:

CSVfileisgeneratedanddownloaded

Dept. of CSE Page 30


FSD Laboratory 2024

9.Develop example Django app that performs PDF generation for any models created in previous
laboratory component.

views.py in app
fromdjango.httpimportHttpResponse
fromdjango.shortcutsimportrender

fromreportlab.pdfgenimportcanvas

defconstruct_pdf_from_model(request):
courses=Course.objects.all()
response=HttpResponse(content_type="application/pdf")
response['Content-Disposition'] ='attachment;filename="courses_data.pdf"'
c=canvas.Canvas(response)
c.drawString(70,720,"Course Name")
c.drawString(170,720,"Course Code")
c.drawString(270,720,"Credits")
y=660
forcourseincourses:
c.drawString(70,y,course.course_name)
c.drawString(170,y,course.course_code)
c.drawString(270,y,str(course.course_credits))
y=y-60
c.showPage()
c.save()
returnresponse

urls.py in project
fromdjango.contribimportadmin
fromdjango.urlsimportpath, re_path

fromap1.viewsimportreg,add_project ,course_search
fromap1.viewsimportStudentListView, StudentDetailView
fromap1.viewsimportStudentListView,StudentDetailView,construct_csv
fromap1.viewsimportconstruct_csv_from_model
fromap1.viewsimportconstruct_pdf_from_model

admin.site.site_header="My Site Header"


admin.site.site_title="My Site Title"
admin.site.index_title="My Site Index"
urlpatterns= [
path('admin/', admin.site.urls),
path('reg/', reg),
path('add_project/', add_project),
path('course_search/', course_search),
path('student_list/', StudentListView.as_view()),

Dept. of CSE Page 31


FSD Laboratory 2024

path('student_detail/<int:pk>/', StudentDetailView.as_view()),
path('construct_csv/', construct_csv),
path('construct_csv_from_model/', construct_csv_from_model),
path('construct_pdf_from_model/', construct_pdf_from_model),
]

 pip install reportlab

Output:

PDFfileisgeneratedanddownloaded

Dept. of CSE Page 32


FSD Laboratory 2024

Module-5
10. Develop a registration page for student enrolment as done in Module 2 but without page refresh
using AJAX.

Views.py in app

fromdjango.http import HttpResponse


fromdjango.shortcuts import render
defregaj(request):
ifrequest.method=="POST":
sid=request.POST.get("sname")
cid=request.POST.get("cname")
student=Student.objects.get(id=sid)
course=Course.objects.get(id=cid)
res=student.enrolment.filter(id=cid)
ifres:
returnHttpResponse("<h1>Student already enrolled</h1>")
student.enrolment.add(course)
returnHttpResponse("<h1>Student enrolled successfully</h1>")

else:
students=Student.objects.all()
courses=Course.objects.all()

returnrender(request,"regaj.html",{"students":students, "courses":courses})

Create templatesfolder in app:

regaj.html
{% load static %}
<html>
<body>
<formmethod="post"action="">
{% csrf_token %}
Student Name
<selectname="sname"id="sname">
{%for student in students %}
<optionvalue="{{student.id}}">{{student.student_name}}</option>
{% endfor %}
</select><br>
Course Name
<selectname="cname"id="cname">
{%for course in courses %}

Dept. of CSE Page 33


FSD Laboratory 2024

<optionvalue="{{course.id}}">{{course.course_name}}</option>
{% endfor %}

</select><br>
<spanid="ans"></span>
<inputtype="button"value="Enroll"id="ebtn">
</form>
<scriptsrc="{% static 'jquery.js' %}"></script>
<script>
$(document).ready(function(){
$("#ebtn").click(function(){
varsname = $("#sname").val();
varcname = $("#cname").val();
$.ajax({
type:"POST",
url:"/regaj/",
data: {sname:sname, cname:cname,
csrfmiddlewaretoken:"{{ csrf_token}}"
},
success:function(response){
$("#ans").html(response)
}
});
});
});
</script>
</body>
</html>

Urls.py in project
fromdjango.contribimportadmin
fromdjango.urlsimportpath, re_path
fromap1.viewsimportcbox, expr,regaj

urlpatterns= [
path('secretadmin/', admin.site.urls),
path('expr/', expr),
path('cbox/', cbox),
path('regaj/',regaj),

Dept. of CSE Page 34


FSD Laboratory 2024

Note: create static folder in app and create ‘jquery.js’ file in static folder.
Download jquery:

 open the uncompressed development version of jQuery 3.7.1


 Copy the code from above link and paste it into ‘jquery.js’ file.

Dept. of CSE Page 35


FSD Laboratory 2024

Output:

Dept. of CSE Page 36


FSD Laboratory 2024

11. Develop a search application in Django using AJAX that displays courses enrolled by a student being
searched.

Views.py in app
fromdjango.http import HttpResponse
fromdjango.shortcuts import render

defcourse_search_ajax(request):
ifrequest.method=="POST":
cid=request.POST.get("cname")
s=Student.objects.all()
student_list=list()
forstudentins:
ifstudent.enrolment.filter(id=cid):
student_list.append(student)
iflen(student_list)==0:
returnHttpResponse("<h1>No Students enrolled</h1>")
returnrender(request,"selected_students.html",{"student_list":student_list})

else:
courses=Course.objects.all()
returnrender(request,"course_search_aj.html",{"courses":courses})

Create templatesfolder in app:


course_search_aj.html
{% load static %}
<html>
<body>
<formmethod="POST"action="">
Courses
{% csrf_token %}
<selectname="cname"id="cname">
{%for course in courses %}
<optionvalue="{{course.id}}">{{course.course_name}}</option>
{% endfor %}
</select>
<inputtype="button"value="Search"id="serbtn">
<spanid="result"></span>
</form>
</body>
<scriptsrc="{% static 'jquery.js' %}"></script>
<script>
$(document).ready(function(){
$("#serbtn").click(function(){
varcname = $("#cname").val();

Dept. of CSE Page 37


FSD Laboratory 2024

$.ajax({
url:"/course_search_ajax/",
type:"POST",
data: {cname:cname,csrfmiddlewaretoken:"{{csrf_token }}"},
success:function(response){
$("#result").html(response);
}
});
});
});
</script>
</html>

Urls.py in project
fromdjango.contribimportadmin
fromdjango.urlsimportpath, re_path
fromap1.viewsimportcbox, expr,regaj,course_search_ajax
urlpatterns= [
path('secretadmin/', admin.site.urls),
path('expr/', expr),
path('cbox/', cbox),
path('regaj/',regaj),
path('course_search_ajax/', course_search_ajax),
]

Output:

Dept. of CSE Page 38

You might also like