21CS62 Lab-Manual
21CS62 Lab-Manual
21CS62 Lab-Manual
LAB MANUAL
Prepared By
Veena G, Jagadamba A
Asst. Professor
Dept. of CSE
Vision and Mission of the Institute
Vision
To become a leading institute for quality technical education and research with ethical values.
Mission
M1: To continually improve quality education system that produces thinking engineers having
good technical capabilities with human values.
M2: To nurture a good eco-system that encourages faculty and students to engage in meaningful
research and development.
M3: To strengthen industry institute interface for promoting team work, internship and
entrepreneurship.
M4: To enhance educational opportunities to the rural and weaker sections of the society to equip
with practical skills to face the challenges of life.
Mission
M1: To nurture a positive environment with state of art facilities conducive for deep learning
and meaningful research and development.
M2: To enhance interaction with industry for promoting collaborative research in emerging
technologies.
M3: To strengthen the learning experiences enabling the students to become ethical professionals
with good interpersonal skills, capable of working effectively in multi-disciplinary teams.
PROGRAM EDUCATIONAL OBJECTIVES (PEOS)
PEO 1: Successful and ethical professionals in IT and ITES industries contributing to societal
progress.
PEO 2: Engaged in life-long learning, adapting to changing technological scenarios.
PEO 3: Communicate and work effectively in diverse teams and exhibit leadership qualities.
Module 1:
Installation of Python, Django and Visual Studio code editors can be demonstrated.
Creation of virtual environment, Django project and App should be demonstrated
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.
Module 2:
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.
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.
7. Develop a Model form for student that contains his topic chosen for project,
languages used and duration with a model called project.
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.
9. Develop example Django app that performs CSV and PDF generation for any
models created in previous laboratory component.
Module 5:
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.
Table of contents
Exp Experiments Page
. No.
No.
1
7
Fullstack Development Laboratory 2023-24
Laboratory Component - 1:
1. Installation of Python, Django and Visual Studio code editors can be demonstrated.
2. Creation of virtual environment, Django project and App should be demonstrated
3. Develop a Django app that displays current date and time in server
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.
Installation
a) Python:
1. Download the latest Python installer from https://www.python.org/downloads/. (Python
3.11.5 preferred).
2. Run the installer and follow the on-screen instructions. Ensure "Add Python to PATH" is
checked for easy access from the command line.
3. Open a command prompt or terminal and type python --version to verify installation.
Update pip in the virtual environment by running the following command prompt:
python -m pip install --upgrade pip
12. Change directory to webproject1 and create Django app use the following command (A
project can have many apps)
python manage.py startapp app1
Program 1
Develop a Django app that displays current date and time in server and date and time
with <offset> hours ahead and <offset> hours before as an offset of current date and
time in server.
Before executing create a Django project called dateproj and create Django app called dateapp
# views.py of dateapp
from datetime import datetime, timedelta
from django.http import HttpResponse
def current_datetime(request):
return HttpResponse(datetime.now())
def hours_ahead(request,offset):
current_datetime = datetime.now()
datetime_ahead = current_datetime + timedelta(hours=int(offset))
datetime_before = current_datetime - timedelta(hours=int(offset))
display = "<h1>Date and Time Offset</h1>"
display += "<p>Current Date and Time: "+str(current_datetime)+"</p>"
display +="<p>Date and Time "+offset+" Hours Ahead: "+ str(datetime_ahead) +"</p>"
display +="<p>Date and Time "+offset+" Hours Before: "+str(datetime_before) +"</p>"
return HttpResponse(display)
# urls.py of dateproj
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('date/', include('dateapp.urls')),
]
# create urls.py in dateapp
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^time/$',views.current_datetime,name="current_datetime" ),
re_path(r'^time/plus/(?P<offset>\d{1,2})/$',views.hours_ahead,name="hours_ahead" ),]
Program 2
Develo
p a simple Django app that displays an unordered list of fruits and ordered list of
selected students for an event
Before executing create a Django project and app, you can use previously created project and can
create a new app called app2 inside previously created project.
Create a folder called templates inside app2 and create a HTML fruits_students.html file.
<html>
<head>
<title>Fruits and Students</title>
</head>
<body>
<h1>Unordered list of fruits</h1>
<ul>
{% for fruit in data.fruits %}
<li>{{fruit}}</li>
{% endfor %}
</ul>
<h1>List of selected students for event {{data.event}} </h1>
<ol>
{% for student in data.students %}
<li>{{student}}</li>
{% endfor %}
</ol>
</body>
</html>
Output
Program 3
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.
Before executing create a Django project and app, you can use previously created project and can
create a new app called app3 inside previously created project.
Create a folder called templates inside app3 and create a HTML layout.html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}My Website{% endblock %}</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
header {
background-color: #333;
color: #fff;
padding: 10px;
}
nav ul {
list-style-type: none;
padding: 0;
}
nav ul li {
display: inline;
margin-right: 20px;
}
nav ul li a {
text-decoration: none;
color: #fff;
}
main {
padding: 20px;
}
footer {
background-color: #333;
color: #fff;
text-align: center;
padding: 10px;
position: fixed;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="{% url 'home' %}">Home</a></li>
<li><a href="{% url 'about_us' %}">About Us</a></li>
<li><a href="{% url 'contact_us' %}">Contact Us</a></li>
</ul>
</nav>
</header>
<main>
{% block content %}
{% endblock %}
</main>
<footer>
<p>© 2024 My Website. All rights reserved. </p>
<p>Developed by Vemana IT</p>
</footer>
</body>
</html>
{% extends 'layout.html' %}
{% block title %}Home{% endblock %}
{% block content %}
<h1>Welcome to Vemana Institute of Technology</h1>
<p>Empowering students with a blend of knowledge and innovation.</p>
<p>Nestled in the bustling city of Bengaluru, our campus is a hub of academic excellence and
cutting-edge research.</p>
<h2>Discover Your Potential</h2>
<strong>Undergraduate Programs:</strong> Dive into our diverse range of engineering
courses designed to fuel your passion and drive innovation.
<p>Join our vibrant community where ideas flourish and inventions come to life in our state-of-
the art labs and research centers.</p>
<p>Benefit from our strong industry ties and placement programs that open doors to exciting
career
opportunities.</p>
{% endblock %}
{% extends 'layout.html' %}
{% block title %}About Us{% endblock %}
{% block content %}
<h1>Our Legacy</h1>
<p>Founded on the principles of quality education and societal contribution, we've been at the
forefront of technological education for over four decades.</p>
<h1>Vision and Mission</h1>
<p>To become a leading institute by providing quality technical education and research with
ethical values.</p>
<p>Our mission is to continually improve quality education system that produces thinking
engineers having good technical capabilities with human values.</p>
<h1>Campus Life</h1>
<p>Experience a dynamic campus life enriched with cultural activities, technical clubs, and
path('about_us/', views.about_us,name="about_us" ),
path('contact_us/', views.contact_us,name="contact_us" ),
Output
Program 4
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.
Before executing, create a Django project and app, you can use previously created project and
can create a new app called app4 inside previously created project.
path('app4/', include('app4.urls')),
Create a folder called templates inside app4 and create html files.
Create a file called forms.py and urls.py inside app4.
padding: 0;
}
nav ul li {
display: inline;
margin-right: 20px;
}
nav ul li a {
text-decoration: none;
color: #fff;
}
main {
padding: 20px;
}
footer {
background-color: #333;
color: #fff;
text-align: center;
padding: 10px;
position: fixed;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="{% url 'add_student' %}">Add Student</a></li>
<li><a href="{% url 'add_course' %}">Add Course</a></li>
<li><a href="{% url 'register_student' %}">Register Student</a></li>
<li><a href="{% url 'course_list' %}">Courses</a></li>
</ul>
</nav>
</header>
<main>
{% block content %}
{% endblock %}
</main>
<footer>
<p>© 2024 My Website. All rights reserved. </p>
<p>Developed by Vemana IT</p>
</footer>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------
<!-- add_student.html -->
{% extends 'mylayout.html' %}
{% block title %}Add Student{% endblock %}
{% block content %}
<h1>Add Student</h1>
<form method="post">
<!-- Cross Site Request Forgery protection -->
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
------------------------------------------------------------------------------------------------------------------------------------
<!--add_course.html -->
{% extends 'mylayout.html' %}
{% block title %}Add Course{% endblock %}
{% block content %}
<h1>Add Course</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Add Course</button>
</form>
{% endblock %}
------------------------------------------------------------------------------------------------------------------------------------
<!-- confirmation.html -->
{% extends 'mylayout.html' %}
{% block title %}Confirmation{% endblock %}
{% block content %}
<h4>{{message}} </h4>
{% endblock %}
------------------------------------------------------------------------------------------------------------------------------------
<!-- register_student.html -->
{% extends 'mylayout.html' %}
{% block title %}Register Student{% endblock %}
{% block content %}
<h1>Register Student to Course</h1>
<form method="POST" >
{% csrf_token %}
{% if error_message%}
<font color="red">{{error_message}}</font>
<br>
<br>
{% endif %}
<label for="student_name">Student Name:</label>
<input type="text" id="student_name" name="student_name" required>
<br>
<br>
<label for="course_id">Select Course:</label>
<select name="course_id" id="course_id">
{% for course in courses %}
<option value="{{ course.id }}">{{ course.name }}</option>
{% endfor %}
</select>
<br>
<br>
<button type="submit" >Register</button>
{% endblock %}
------------------------------------------------------------------------------------------------------------------------------------
<!-- courses.html -->
{% extends 'mylayout.html' %}
{% block title %}Courses{% endblock %}
{% block content %}
<h1>Course List</h1>
<ul >
{% for course in courses %}
<li >
<a href="{% url 'students_list' course.course_id %}">{{ course.name }} (ID: {{course.course_id }})</a>
</li>
{% endfor %}
</ul>
{% endblock %}
------------------------------------------------------------------------------------------------------------------------------------
<!-- students_list.html -->
{% extends 'mylayout.html' %}
{% block title %}Add Course{% endblock %}
{% block content %}
#models.py
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100,unique=True)
date_of_birth = models.DateField(
default='1900-01-01', blank=False, null=False) # Set a default date
email = models.EmailField(
default='[email protected]', blank=False, null=False) # Set a default email
def __str__(self):
return self.name
class Course(models.Model):
name = models.CharField(max_length=100,unique=True)
students = models.ManyToManyField(Student, related_name='courses')
course_id = models.IntegerField(default=0,unique=True)
def __str__(self):
return self.name
------------------------------------------------------------------------------------------------------------------------------------
In command prompt under project directory, execute the following commands.
py manage.py makemigrations app4
py manage.py migrate app4
------------------------------------------------------------------------------------------------------------------------------------
#forms.py
from .models import Student
from django import forms
from .models import Course
class CourseForm(forms.ModelForm):
class Meta:
model = Course
fields = ['name', 'course_id']
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['name', 'date_of_birth', 'email']
------------------------------------------------------------------------------------------------------------------------------------
#urls.py
from django.urls import path
from . import views
urlpatterns = [
path('add_student/',views.add_student,name="add_student" ),
path('add_course/',views.add_course,name="add_course" ),
path('register/', views.register_student, name='register_student'),
path('courses/', views.course_list, name='course_list'),
path('students_list/<int:course_id>/', views.students_list, name='students_list'),
------------------------------------------------------------------------------------------------------------------------------------
#views.py
from django.shortcuts import render, get_object_or_404
from .forms import StudentForm, CourseForm
from .models import Student, Course
def add_student(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()
# Redirect to a view that lists all students
return render(request, 'confirmation.html', {'message': "Student added Successfully..."})
else:
form = StudentForm()
return render(request, 'add_student.html', {'form': form})
def add_course(request):
if request.method == 'POST':
form = CourseForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'confirmation.html', {'message': "Course added Successfully..."})
else:
form = CourseForm()
return render(request, 'add_course.html', {'form': form})
def register_student(request):
if request.method == 'POST':
student_name = request.POST.get('student_name')
course_id = request.POST.get('course_id')
# Validate that both student_name and course_id are provided
if not student_name or not course_id:
return render(request, 'register_student.html', {'courses': Course.objects.all(),
'error_message': 'Please provide both student name and select a course.'})
try:
# Retrieve the course based on course_id or return 404 if not found
except Course.DoesNotExist:
return render(request, 'register_student.html', {'courses': Course.objects.all(),
'error_message': 'Invalid course ID. Please select a valid course.'})
return render(request, 'register_student.html', {'courses': Course.objects.all()})
def course_list(request):
courses = Course.objects.all()
return render(request, 'courses.html', {'courses': courses})
Output
Program 5
For student and course models created in Lab experiment for Module2, register admin
interfaces, perform migrations and illustrate data entry through admin forms.
# admin.py
from django.contrib import admin
from .models import Student,Course
class StudentAdmin(admin.ModelAdmin):
pass
class CourseAdmin(admin.ModelAdmin):
pass
# Register your models here.
admin.site.register(Course, CourseAdmin)
admin.site.register(Student, StudentAdmin)
In command prompt change directory to your project folder. Execute the following command to
create super user.
py manage.py createsuperuser
Access the admin pages using the following url.
http://localhost:8000/admin
Course modification
Course listing
Course deletion
Program 6
Develop a Model form for student that contains his topic chosen for project, languages
used an duration with a model called project.
{% if student %}
<p>Name: {{student.name}}</p>
<p>Date of Birth: {{student.date_of_birth}}</p>
<p>Email: {{student.email}}</p>
{% else %}
<p>Student Details are not found</p>
{% endif %}
{% if courses %}
<p> Course details </p>
<ul>
{% for c in courses%}
<li>
{{c.name}}
</li>
{% endfor%}
</ul>
{% else %}
<p> Not registered for any courses </p>
{% endif %}
{% if projects %}
<p> Project details </p>
<ul>
{% for p in projects%}
<li>{{p.ptitle}}</li>
{% endfor%}
</ul>
{% else %}
<p> Not registered for any projects </p>
{% endif %}
{% endblock %}
# models.py
class Project(models.Model):
student=models.ForeignKey(Student,on_delete=models.CASCADE)
ptitle=models.CharField(max_length=30)
planguage=models.CharField(max_length=30)
pduration=models.IntegerField()
# forms.py
class ProjectForm(forms.ModelForm):
class Meta:
model=Project
fields=['student','ptitle','planguage','pduration']
# views.py
def register_proj(request):
if request.method=="POST":
form=ProjectForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'confirmation.html', {'message': "Project Data Successfully
saved..."})
else:
form=ProjectForm()
return render(request, "project_reg.html",{'form':form})
def students_details(request,student_id):
student = Student.objects.filter(id=student_id).first()
if(student) :
courses = Course.objects.filter(students__id=student.id)
projects = Project.objects.filter(student=student.id)
return render(request, 'student_details.html', locals())
Output