Django Lab Programs
Django Lab Programs
https://tinyurl.com/DjangoFDP
1.3: Develop a Django app that displays current date and time in server
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 (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')
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">
© 2024 My Website. All rights reserved. Designed & 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")
12
views.py (inside members app):
from members.models import *
from django.shortcuts import render
def course_list(request):
courses = Course.objects.all()
return render(request, 'course_list.html', {'courses' : courses})
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
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
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'),
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
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()
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