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

FSD Lab Manual 2024

Uploaded by

harshithpavan64
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)
35 views38 pages

FSD Lab Manual 2024

Uploaded by

harshithpavan64
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 INFORMATION SCIENCE & ENGINEERING

FULLSTACK DEVELOPMENT
INTEGRATED LAB MANUAL [21CSL62]
(VI SEM CBCS, 2021 SCHEME)
Prepared
By
Dr. Ambika L G
Associate professor
Dept. of ISE

S.J.C.INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION 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: MVC based Web Designing


Laboratory Component:
1. Installation of Python, Django and Visual Studio code editors can be
demonstrated.

Python download and installation Link:


https://www.python.org/downloads/
Visual Studio Code download and installation link:
https://code.visualstudio.com/
Django installation:
Open a command prompt and type following command: pip install
django

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


demonstrated
Follow these steps
1. Install the Python extension.- Open VS Code IDE and click extensions there
automatically u will be shown Python extension (Make sure you are connected to
Internet)
2. On your file system, create a project folder
3. In that folder, use the following command (as appropriate to your computer) to
create a virtual environment named env based on your current interpreter:
# Windows

4. Open the project folder in VS Code by running code ., or by running VS Code


and using the File > Open Folder command.
5. In VS Code, open the Command Palette (View > Command Palette or
(Ctrl+Shift+P)). Then select the Python: Select Interpreter command:

6. The command presents a list of available interpreters that VS Code can locate
automatically (your list will vary; if you don't see the desired interpreter, see

Dept. of ISE Page 4


FSD Laboratory 2024

Configuring Python environments). From the list, select the virtual environment in
your project folder that starts with ./env or .\env:
7. Create a New Terminal : In Menu Terminal -> New Terminal option

Creating project:
1. Create a django project -

Type following command in the terminal opened:


django-admin startproject p .

(dot following project name is important which refers to current directory)

This startproject command assumes (by use of . at the end) that the current folder is
your project folder, and creates the following within it:
● manage.py: The Django command-line administrative utility for the project.
You run administrative commands for the project using python manage.py
<command> [options].
● A subfolder named p which contains the following files:
o init .py: an empty file that tells Python that this folder is a Python
package.
o wsgi.py: an entry point for WSGI-compatible web servers to serve your
project. You typically leave this file as-is as it provides the hooks for
production web servers.
o settings.py: contains settings for Django project, which you modify in the
course of developing a web app.
o urls.py: contains a table of contents for the Django project, which you
also modify in the course of development.

2. To verify the Django project, make sure your virtual environment is activated, then
start Django's development server using the
command python manage.py runserver. The server runs on the default port 8000,
and you see output like the following output in the terminal window:
Verify server by typing:
python manage.py runserver

Dept. of ISE Page 5


FSD Laboratory 2024

When you run the server the first time, it creates a default SQLite database in the file
db.sqlite3, which is intended for development purposes but can be used in production for
low-volume web apps. Also, Django's built-in web server is intended only for local
development purposes. When you deploy to a web host, however, Django uses the host's
web server instead. The wsgi.py module in the Django project takes care of hooking into
the production servers.
If you want to use a different port than the default 8000, specify the port number on the
command line, such as python manage.py runserver 5000.
3. When you're done, close the browser window and stop the server in VS Code
using Ctrl+C as indicated in the terminal output window.
4. In the VS Code Terminal with your virtual environment activated, run the
administrative utility's startapp command in your project folder (where
manage.py resides):

5. The command creates a folder called lab1 that contains a number of code
files and one subfolder. Of these, you frequently work with views.py (that contains
the functions that define pages in your web app) and models.py (that
contains classes defining your data objects). The migrations folder is used by
Django's administrative utility to manage database versions. There are also the
files apps.py (app configuration), admin.py (for creating an administrative
interface), and tests.py (for unit tests).

Dept. of ISE Page 6


FSD Laboratory 2024

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

Views.py in app
from django.shortcuts import render
from django.http import HttpResponse

import datetime
def current_datetime(request):
dt = datetime.datetime.now()
resp = "<h1>Current date and time is %s</h1>" %(dt)
return HttpResponse(resp)

urls.py in project
from django.contrib import admin
from django.urls import path
from ap1.views import current_datetime

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

Output:

Dept. of ISE 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
from django.shortcuts import render
from django.http import HttpResponse
import datetime
def current_datetime(request):
dt = datetime.datetime.now()
resp = "<h1>It is now %s.</h1>" %(dt)
return HttpResponse(resp)

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

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

urls.py in project
from django.contrib import admin
from django.urls import path
from ap1.views import current_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 ISE 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


from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader

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

URLS.py in app name members


from django.urls import path
from . import views

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

URLS.py in project name store


from django.contrib import admin
from django.urls import path , include

from members.views import showlist


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

Create templates folder in app:


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

Dept. of ISE Page 9


FSD Laboratory 2024

{% for fruit in fruits %}


<li>{{ fruit }}</li>
{% endfor %}
</ul>
<h1 id="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 ISE 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
from django.http import HttpResponse
from django.shortcuts import render
from django.template import Context, Template
def home(request):
return render(request,'home.html')

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

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

URLS.py in app3
from django.urls import path

from . import views

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
from django.contrib import admin
from django.urls import path,include

urlpatterns = [

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

Dept. of ISE Page 11


FSD Laboratory 2024

Create templates folder in app:


layout.html file in templates folder
<html>
<title>{% block title %} {% endblock %} </title>
<style type="text/css">
nav {background-color: lightblue;padding:10px}
</style>
<body>
<nav>
<a href="/home/">Home</a>|
<a href="/aboutus/">About Us</a>|
<a href="/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 ISE 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 ISE 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 templates folder in app:

course_search.html file in templates folder

<html>
<body>
<form method="POST" action="">
Courses
{% csrf_token %}
<select name="cname">
{%for course in courses %}
<option value="{{course.id}}">{{course.course_name}}</option>
{% endfor %}
</select>
<input type="submit" value="Search">
</form>
</body>
</html>

selected_students.html

<html>
<body>
<table border>
<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 ISE Page 14


FSD Laboratory 2024

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

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

Views.py in app

from django.http import HttpResponse


from django.shortcuts import render

from ap1.models import Course, ProjectReg, Student

def reg(request):
if request.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)
if res:
return HttpResponse("<h1>Student already enrolled</h1>")
student.enrolment.add(course)
return HttpResponse("<h1>Student enrolled successfully</h1>")

else:
students=Student.objects.all()
courses=Course.objects.all()
return render(request,"reg.html",{"students":students, "courses":courses})
def course_search(request):
if request.method=="POST":
cid=request.POST.get("cname")

Dept. of ISE Page 15


FSD Laboratory 2024

s=Student.objects.all()
student_list=list()
for student in s:
if student.enrolment.filter(id=cid):
student_list.append(student)
if len(student_list)==0:
return HttpResponse("<h1>No Students enrolled</h1>")
return render(request,"selected_students.html",{"student_list":student_list})

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

models.py in app
from django.db import models
from django.forms import ModelForm

# Create your models here.


class Course(models.Model):
course_code=models.CharField(max_length=40)
course_name=models.CharField(max_length=100)
course_credits=models.IntegerField()
def __str__(self):
return self.course_name

class Student(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):
return self.student_name+"("+self.student_usn+")"

urls.py in project

from django.contrib import admin


from django.urls import path, re_path

from ap1.views import reg, 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 ISE Page 16


FSD Laboratory 2024

Output:

Perform migrations before running:

 python manage.py makemigrations

 python manage.py migrate

 Database input:Insert student and courses record in db.sqlite3 or


PhPmyadmin

Dept. of ISE Page 17


FSD Laboratory 2024

Back End

Dept. of ISE 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

make following changes to admin.py

from django.contrib import admin

from ap1.models import Course, Student

# Register your models here.


#admin.site.register(Student)
@admin.register(Student)
class StudentAdmin(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

from django.http import HttpResponse


from django.shortcuts import render

from ap1.models import Course, ProjectReg, Student

def reg(request):
if request.method == "POST":
sid=request.POST.get("sname")

Dept. of ISE 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)
if res:
return HttpResponse("<h1>Student already enrolled</h1>")
student.enrolment.add(course)
return HttpResponse("<h1>Student enrolled successfully</h1>")

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

def course_search(request):
if request.method=="POST":
cid=request.POST.get("cname")
s=Student.objects.all()
student_list=list()
for student in s:
if student.enrolment.filter(id=cid):
student_list.append(student)
if len(student_list)==0:
return HttpResponse("<h1>No Students enrolled</h1>")
return render(request,"selected_students.html",{"student_list":student_list})

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

urls.py in project

from django.contrib import admin


from django.urls import path, re_path

from ap1.views import reg,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 ISE Page 20


FSD Laboratory 2024

Changes to models.py in app

from django.db import models


from django.forms import ModelForm

# Create your models here.


class Course(models.Model):
course_code=models.CharField(max_length=40)
course_name=models.CharField(max_length=100)
course_credits=models.IntegerField()
def __str__(self):
return self.course_name

class Student(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):
return self.student_name+"("+self.student_usn+")"

Create templates folder in app:

course_search.html file in templates folder

<html>
<body>
<form method="POST" action="">
Courses
{% csrf_token %}
<select name="cname">
{%for course in courses %}
<option value="{{course.id}}">{{course.course_name}}</option>
{% endfor %}
</select>
<input type="submit" value="Search">
</form>
</body>
</html>

selected_students.html

<html>
<body>
<table border>
<tr>
<th>Student Name</th>

Dept. of ISE 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>
<form method="post" action="">
{% csrf_token %}
Student Name
<select name="sname">
{%for student in students %}
<option value="{{student.id}}">{{student.student_name}}</option>
{% endfor %}
</select><br>
Course Name
<select name="cname">
{%for course in courses %}
<option value="{{course.id}}">{{course.course_name}}</option>
{% endfor %}

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

Perform remigrations before running:

python manage.py makemigrations python

manage.py migrate

Dept. of ISE Page 22


FSD Laboratory 2024

Output:

Dept. of ISE 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
from django.db import models
from django.forms import ModelForm

# Create your models here.

class Course(models.Model):
course_code=models.CharField(max_length=40)
course_name=models.CharField(max_length=100)
course_credits=models.IntegerField()
def __str__(self):
return self.course_name

class Student(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):
return self.student_name+"("+self.student_usn+")"

class Project(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()

class ProjectReg(ModelForm):
required_css_class="required"
class Meta:
model=Project
fields=['student','ptopic','plangauges','pduration']

views.py in app

from django.http import HttpResponse


from django.shortcuts import render

from ap1.models import Course, ProjectReg, Student

def add_project(request):
if request.method=="POST":
form=ProjectReg(request.POST)
if form.is_valid():
form.save()

Dept. of ISE Page 24


FSD Laboratory 2024

return HttpResponse("<h1>Record inserted successfully</h1>")


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

Create templates folder in app:

add_project.html inside templates folder

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

urls.py in project
from django.contrib import admin
from django.urls import path, re_path

from ap1.views import reg,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

 python manage.py migrate

Dept. of ISE Page 25


FSD Laboratory 2024

Output:

BackEnd

Dept. of ISE 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
from django.views import generic
class StudentListView(generic.ListView):
model=Student
template_name="student_list.html"

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

Create templates folder in app:


student_list.html inside templates folder
<html>
<body>
{% if student_list %}
<table border>
<tr>
<th>USN</th>
<th>Courses Enrolled</th>
</tr>
{% for student in student_list %}
<tr>
<td><a href="/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 ISE 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

from django.contrib import admin


from django.urls import path, re_path

from ap1.views import reg,add_project ,course_search


from ap1.views import StudentListView, 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 ISE 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
from django.http import HttpResponse
from django.shortcuts import render

import csv
def construct_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","Course Code","Credits"])
for course in courses:
writer.writerow([course.course_name,course.course_code,course.course_credits])
return response

urls.py in project
from django.contrib import admin
from django.urls import path, re_path

from ap1.views import reg,add_project ,course_search


from ap1.views import StudentListView, StudentDetailView
from ap1.views import StudentListView,StudentDetailView,construct_csv
from ap1.views import construct_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 ISE Page 29


FSD Laboratory 2024

Output:

CSV file is generated and downloaded

Dept. of ISE 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
from django.http import HttpResponse
from django.shortcuts import render

from reportlab.pdfgen import canvas

def construct_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
for course in courses:
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()
return response

urls.py in project
from django.contrib import admin
from django.urls import path, re_path

from ap1.views import reg,add_project ,course_search


from ap1.views import StudentListView, StudentDetailView
from ap1.views import StudentListView,StudentDetailView,construct_csv
from ap1.views import construct_csv_from_model
from ap1.views import construct_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 ISE 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:

PDF file is generated and downloaded

Dept. of ISE 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

from django.http import HttpResponse


from django.shortcuts import render
def regaj(request):
if request.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)
if res:
return HttpResponse("<h1>Student already enrolled</h1>")
student.enrolment.add(course)
return HttpResponse("<h1>Student enrolled successfully</h1>")

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

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

Create templates folder in app:

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

Dept. of ISE Page 33


FSD Laboratory 2024

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

</select><br>
<span id="ans"></span>
<input type="button" value="Enroll" id="ebtn">
</form>
<script src="{% static 'jquery.js' %}"></script>
<script>
$(document).ready(function(){
$("#ebtn").click(function(){
var sname = $("#sname").val();
var cname = $("#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
from django.contrib import admin
from django.urls import path, re_path
from ap1.views import cbox, expr, regaj

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

Dept. of ISE 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 ISE Page 35


FSD Laboratory 2024

Output:

Dept. of ISE 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
from django.http import HttpResponse
from django.shortcuts import render

def course_search_ajax(request):
if request.method=="POST":
cid=request.POST.get("cname")
s=Student.objects.all()
student_list=list()
for student in s:
if student.enrolment.filter(id=cid):
student_list.append(student)
if len(student_list)==0:
return HttpResponse("<h1>No Students enrolled</h1>")
return render(request,"selected_students.html",{"student_list":student_list})

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

Create templates folder in app:


course_search_aj.html
{% load static %}
<html>
<body>
<form method="POST" action="">
Courses
{% csrf_token %}
<select name="cname" id="cname">
{%for course in courses %}
<option value="{{course.id}}">{{course.course_name}}</option>
{% endfor %}
</select>
<input type="button" value="Search" id="serbtn">
<span id="result"></span>
</form>
</body>
<script src="{% static 'jquery.js' %}"></script>
<script>
$(document).ready(function(){
$("#serbtn").click(function(){
var cname = $("#cname").val();

Dept. of ISE 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
from django.contrib import admin
from django.urls import path, re_path
from ap1.views import cbox, 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 ISE Page 38

You might also like