FSD Lab Manual 2024
FSD Lab Manual 2024
S J C INSTITUTE OF TECHNOLOGY
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:
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
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
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:
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:
Module-2
3. Develop a simple Django app that displays an unordered list of fruits and ordered list
of selected students for an event
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}
)
urlpatterns= [
path('showlist/', views.showlist, name='showlist'),
frommembers.viewsimportshowlist
urlpatterns= [
path('admin/', admin.site.urls),
path('', include('members.urls')),
]
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:
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')),
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:
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.
<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
<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
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")
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
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)
]
Output:
pythonmanage.py migrate
Databaseinput:Insertstudentandcoursesrecordin db.sqlite3 or
PhPmyadmin
Back End
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
makefollowingchangestoadmin.py
fromdjango.contribimportadmin
fromap1.modelsimportCourse, Student
Views.py in app
fromdjango.httpimportHttpResponse
fromdjango.shortcutsimportrender
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")
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)
]
fromdjango.dbimportmodels
fromdjango.formsimportModelForm
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+")"
<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
<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>
running:python manage.py
Output:
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
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
defadd_project(request):
ifrequest.method=="POST":
form=ProjectReg(request.POST)
ifform.is_valid():
form.save()
<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:
pythonmanage.py migrate
Output:
BackEnd
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"
student_detail.html
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:
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
Output:
CSVfileisgeneratedanddownloaded
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
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),
]
Output:
PDFfileisgeneratedanddownloaded
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
else:
students=Student.objects.all()
courses=Course.objects.all()
returnrender(request,"regaj.html",{"students":students, "courses":courses})
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 %}
<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),
Note: create static folder in app and create ‘jquery.js’ file in static folder.
Download jquery:
Output:
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})
$.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: