0% found this document useful (0 votes)
18 views

Django Lab Programs

Uploaded by

manjunathnlm13
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)
18 views

Django Lab Programs

Uploaded by

manjunathnlm13
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/ 40

Solutions to Laboratory Experiments [Module-wise]

for the course

“Full Stack Development”

https://tinyurl.com/DjangoFDP
1.3: Develop a Django app that displays current date and time in server

views.py (inside members app):


from django.http import HttpResponse
import datetime
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
urls.py (inside members app):
from django.urls import path
path('current-time/', current_datetime),

urls.py (inside project):


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

2
1.4: Develop a Django app that displays date and time four hours ahead and four hours
before as an offset of current date and time in server

views.py (inside members app):


from django.http import HttpResponse
def hours_offset(request, offset):
try:
offset = int(offset)
except ValueError:
raise Http404()
dt1 = datetime.datetime.now() + datetime.timedelta(hours=offset)
dt2 = datetime.datetime.now() - datetime.timedelta(hours=offset)
html = "<html><body>In %s hour(s) ahead, it will be %s.<p>In %s
hour(s) before, it was %s. </body></html>" % (offset, dt1, offset, dt2)
return HttpResponse(html)

urls.py (inside members app):


from django.urls import path
path('hours-offset/', hours_offset),
3
2.1: Develop a simple Django app that displays an unordered list of fruits and
ordered list of selected students for an event

views.py (members):
from django.shortcuts import render
def display_list(request):
fruits = ['Mango','Jackfruit','Apple','Orange']
students = ['Abhay','Sameer','Chaitra','Amar']
context = {'fruits' : fruits, 'students' : students }
return render(request, 'display_list.html', context = context)
urls.py (project):
urls.py (members): from django.contrib import admin
from django.urls import path from django.urls import path, include
from . import views urlpatterns = [
urlpatterns = [ path('members/',
path('list/', views.display_list), include('members.urls')),
] path('admin/', admin.site.urls),
] 4
display_list.html:
<!DOCTYPE html> <h2>Selected Students:</h2>
<html lang="en"> <ol>
<head> {% for student in students %}
<title>Fruit and Student <li>{{student}}</li>
Lists</title> {% endfor %}
</head> </ol>
<body> </body>
<h2>Ordered List of Fruits:</h2> </html>
<ul>
{% for fruit in fruits %}
<li>{{fruit}}</li>
{% endfor %}
</ul>

5
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

views.py (app):
from django.shortcuts import render
def home(request):
return render(request, 'home.html')
def about(request):
return render(request, 'about.html')
def contact(request):
return render(request, 'contact.html')

urls.py: (append it inside urlpatterns)


path('home/', views.home, name='home'),
path('about/', views.about, name='about'),
path('contact/', views.contact, name='contact'),

6
layout.html: li a:hover:not(.active) {
<!DOCTYPE html"> background-color: #111;
<html lang="en"> }
<head> .active {
<meta charset="UTF-8" /> background-color: #04aa6d;
<meta name="viewport" }
content="width=device-width, initial-scale=1.0" /> .footer {
<title>{% block title %}{% endblock %}</title> position: fixed;
<style> left: 0;
ul { bottom: 0;
list-style-type: none; width: 100%;
margin: 0; background-color: blanchedalmond;
padding: 0; color: brown;
overflow: hidden; text-align: center;
background-color: #333; }
} </style>
li { </head>
float: left; <body>
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
7
<header>
<nav>
<ul>
<li><a href="https://sdmcet.ac.in/" target="_blank">Home</a></li>
<li><a href="{% url 'about' %}">About Us</a></li>
<li><a href="{% url 'contact' %}">Contact Us</a></li>
</ul>
</nav>
</header>
{% block content %} {% endblock %}
<footer>
<div class="footer">
&copy; 2024 My Website. All rights reserved. Designed &amp; Developed by SDMIT, Ujire
</div>
</footer>
</body>
</html>

8
home.html:
{% extends 'layout.html' %}
{% block title %}Home - My Website{% endblock %}
{% block content %}
<h1>Welcome to My Website!</h1>
<p>This is the home page content.</p>
{% endblock %}
contact.html:
{% extends 'layout.html' %}
{% block title %}Contact Us - My Website{% endblock %}
{% block content %}
<h1>Contact Us</h1>
<p>This is the contact us page content.</p>
{% endblock %}

9
about.html:
{% extends 'layout.html' %}
{% block title %}About Us - My Website{% endblock %}
{% block content %}
<h1>About Us</h1>
<p>This is the about us page content.</p>
{% endblock %}

10
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.
models.py (inside members app):
from django.db import models
class Course(models.Model):
name = models.CharField(max_length=100)

def __str__(self):
return self.name

class Student(models.Model):
name = models.CharField(max_length=100)
courses = models.ManyToManyField(Course, related_name='students')

def __str__(self):
return self.name

11
$> python manage.py shell
from members.models import Student, Course
# create some courses
course1 = Course.objects.create(name="Math")
course2 = Course.objects.create(name="Science")

# create some students


student1 = Student.objects.create(name="Alice")
student2 = Student.objects.create(name="Bob")
student3 = Student.objects.create(name="Charlie")

# add students to courses


course1.students.add(student1, student2)
course2.students.add(student2, student3)

12
views.py (inside members app):
from members.models import *
from django.shortcuts import render

def course_students(request, course_name):


course = Course.objects.get(name=course_name)
students = course.students.all()
return render(request, 'course_students.html', {'course': course,
'students': students})

def course_list(request):
courses = Course.objects.all()
return render(request, 'course_list.html', {'courses' : courses})

urls.py (inside members app):


path('course_students/<str:course_name>/', views.course_students,
name='course_students'),
path('course_list/', views.course_list),

13
course_students.html (inside templates folder members app):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Course Students</title>
</head>
<body>
<h2>Students Registered for {{ course.name }}</h2>
<ul>
{% for student in students %}
<li>{{ student.name }}</li>
{% endfor %}
</ul>
</body>
</html>

14
course_list.html (inside template folder members app):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"
/>
<title>Courses List</title>
</head>
<body>
<h2>List of Courses</h2>
<ol>
{% for course in courses %}
<li><a href="{% url 'course_students' course.name
%}">{{course.name}}</a></li>
{% endfor %}
</ol>
</body>
</html>
15
3.1: For student and course models created in Lab experiment for Module-2,
register admin interfaces, perform migrations and illustrate data entry through
admin forms
admin.py (inside project):
from django.contrib import admin
from members.models import Course, Student

# Register your models here.


admin.site.register(Course)
admin.site.register(Student)

● Launch the admin interface using the URL: http://127.0.0.1:8000/admin


● Login using superuser credentials
● Demonstrate CRUD operations on Course and Student models

16
3.2: Develop a Model form for student that contains his topic chosen for project,
languages used and duration with a model called project
models.py (inside members app):
# Student already created in Module-2!!!
class Student(models.Model):
name = models.CharField(max_length=100)
courses = models.ManyToManyField(Course, related_name='students')
def __str__(self):
return self.name
class Project(models.Model):
student = models.ForeignKey('Student', on_delete=models.CASCADE)
topic = models.CharField(max_length=100)
languages_used = models.CharField(max_length=100)
duration = models.CharField(max_length=50)
def __str__(self):
return f"{self.student.name}'s Project: {self.topic}"
urls.py (inside members app):
path('project-submission/', project_submission,
name='project_submission'),
path('project-submission/success/', project_submission_success,
name='project_submission_success'),
17
views.py (inside members app):
from django.shortcuts import render, redirect
from members.models import *
from members.forms import *
def project_submission(request):
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
form.save()
return redirect('project_submission_success')
else:
form = ProjectForm()
projects = Project.objects.all()
return render(request, 'project_submission.html', {'form': form,
'projects':projects})

def project_submission_success(request):
return render(request, 'project_submission_success.html') 18
forms.py (inside members app):
from django import forms
from members.models import Project

class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ['student', 'topic', 'languages_used', 'duration']

19
project_submission.html (inside templates folder members app):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Project Submission</title>
</head>
<body>
<h2>Submit Your Project Details</h2>
<form method="post">
{% csrf_token %}
{{ form.as_table }}
<button type="submit">Submit</button>
</form>
<hr />
<h2>List of Submitted Projects</h2>
<table>
<tr><th>Student</th></tr>
20
project_submission.html (contd…):
{% for project in projects %}
<tr>
<td>{{project}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>

21
project_submission_success.html (inside templates folder members app):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Project Submission Success</title>
</head>
<body>
<h2>Project Submission Successful</h2>
<p>Thank you for submitting your project details.</p>
</body>
</html>

22
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
views.py (members app):
from django.views.generic import ListView, DetailView
from members.models import Student

# Generic Views for Students


class StudentListView(ListView):
model = Student
template_name = 'student_list.html'
context_object_name = 'students'

class StudentDetailView(DetailView):
model = Student
template_name = 'student_detail.html'
context_object_name = 'student'

23
urls.py (members app) (append to urlpatterns):
from . import views
path('students/', views.StudentListView.as_view(), name='student-list'),
path('students/<int:pk>/', views.StudentDetailView.as_view(),
name='student-detail'),

student_detail.html (members app):


<!DOCTYPE html>
<html>
<head>
<title>Student Detail</title>
</head>
<body>
<h1>Student Detail</h1>
<p>Name: {{ student.name }}</p>
</body>
</html>

24
student_list.html (members app):
<!DOCTYPE html>
<html>
<head>
<title>Student List</title>
</head>
<body>
<h1>Students List</h1>
<ul>
{% for student in students %}
<li>
<a href="{% url 'student-detail' student.pk %}">{{ student.name }}</a>
</li>
{% endfor %}
</ul>
</body>
</html>

25
4.2: Develop example Django app that performs CSV and PDF generation for any
models created in previous laboratory component
models.py (members app):
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
def __str__(self):
return self.name

urls.py (members app):


from . import views
path('view_publishers/', views.view_publishers),
path('publishers/', views.publishers_csv, name='ExportCSV'),
path('generate_pdf/', views.generate_pdf, name='ExportPDF'), 26
views.py (members app):
def publishers_csv(request):

# Create the HttpResponse object with the appropriate CSV header.


response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=publishers.csv'

# Create the CSV writer using the HttpResponse as the "file."


writer = csv.writer(response)
publishers = Publisher.objects.all()

writer.writerow(['Name','Address','City','Province','Country','Website'])

for p in publishers:
writer.writerow([p.name, p.address, p.city, p.state_province,
p.country, p.website])
return response

def view_publishers(request):
return render(request, 'view_publishers.html') 27
views.py (members app):
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
def generate_pdf(request):
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=publishers.pdf'
publishers = Publisher.objects.all()

doc = SimpleDocTemplate(response, pagesize=letter)

table_data = [["Name","Address","City","State","Country","Website"]]

for p in publishers:
table_data.append([p.name,p.address,p.city,p.state_province,p.country,
p.website])
table = Table(table_data)
# Create the PDF object, using the response object as its "file."
doc.build([table])
return response 28
view_publishers.html (members app):
<html>
<head>
<title> View Publishers </title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
/>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></scrip
t>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></sc
ript>
</head>

29
view_publishers.html (members app):
<body>
<h2>View Publishers as CSV</h2>
<a href="{% url 'ExportCSV' %}" class="btn btn-info" target="_blank"
>Export CSV</a>
<p>
<h2>View Publishers as PDF</h2>
<a href="{% url 'ExportPDF' %}" class="btn btn-info" target="_blank"
>Export PDF</a>
</body>
</html>

30
5.1: Develop a registration page for student enrolment as done in Module-2 but
without page refresh using AJAX
urls.py:
path('list_students/', list_students, name='list-students'),
path('register_student/', register_student, name='register_student'),

views.py:
from django.http import JsonResponse
from .models import Student, Course
from django.views.decorators.csrf import csrf_exempt

def list_students(request):
courses = Course.objects.all()
return render(request, 'list_students.html', {'courses': courses})

31
views.py (contd…):
@csrf_exempt
def register_student(request):
if request.method == 'POST':
course_id = request.POST.get('course_id')
student_name = request.POST.get('student_name')
course = Course.objects.get(pk=course_id)
student, created = Student.objects.get_or_create(name=student_name)
course.students.add(student)
return JsonResponse({'status': 'success'})
return JsonResponse({'status': 'error'})

32
list_students.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Registration</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('.register-btn').click(function () {
var course_id = $(this).data('course-id');
var student_name = $('#student-name').val();
$.ajax({
type: 'POST',
url: '{% url "register_student" %}',

33
list_students.html (contd…):
data: {
'csrfmiddlewaretoken': '{{ csrf_token }}',
'course_id': course_id,
'student_name': student_name
},
dataType: 'json',
success: function (response) {
if (response.status === 'success') {
$('#student-list').load(location.href + '
#student-list');
$('#student-name').val('');
} else {
console.log('Error registering student');
}
},
error: function () {
console.log('Error registering student');
} }); }); });
34
list_students.html (contd…):
</script> </head>
<body>
<h1>Student Registration</h1>
<div> <input type="text" id="student-name" placeholder="Enter student name">
{% for course in courses %}
<button class="register-btn" data-course-id="{{ course.id }}">{{
course.name }}</button> {% endfor %} </div>
<div id="student-list">
{% for course in courses %}
<h2>{{ course.name }} - Registered Students</h2>
<ul>
{% for student in course.students.all %}
<li>{{ student.name }}</li>
{% endfor %}
</ul>
{% endfor %}
</div>
</body>
</html> 35
5.2: Develop a search application in Django using AJAX that displays courses
enrolled by a student being searched
views.py:
from django.http import JsonResponse
def search_student(request):
if request.method == 'GET':
query = request.GET.get('query', '')
try:
student = Student.objects.get(name__iexact=query)
courses = student.courses.all()
course_names = [course.name for course in courses]
return JsonResponse({'courses': course_names})
except Student.DoesNotExist:
return JsonResponse({'error': 'Student not found'})
return JsonResponse({'error': 'Invalid request'})

def search_st(request):
return render(request, 'search_student.html')
36
urls.py:
path('search', search_student, name='search'),
path('student/', search_st),

search_student.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Search Student</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></scrip
t>
</head>
<body>
<h2>Search Student</h2>
<input type="text" id="search-input" />
<button id="search-btn">Search</button>
<div id="result"></div>
37
Search_student.html (contd…):
<script>
$(document).ready(function () {
$("#search-btn").click(function () {
var query = $("#search-input").val();
$.ajax({
type: "GET",
url: "{% url 'search' %}",
data: {
query: query,
},
dataType: "json",
success: function (response) {
if ("error" in response) {
$("#result").html("<p><h3>" + response.error + "</h3></p>");
} else {
var courses = response.courses;
var coursesHtml =
"<h3> List of Courses Registered:</h3><p><ul>";
38
Search_student.html (contd…):
for (var i = 0; i < courses.length; i++) {
coursesHtml += "<li>" + courses[i] + "</li>";
}
coursesHtml += "</ul>";
$("#result").html(coursesHtml);
}
},
error: function (response) {
$("#result").html("<p><h3>" + response.error + "</h3></p>");
},
});
});
});
</script>
</body>
</html>

39
Thank You
40

You might also like