21CS62 Lab-Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 42

Academic Year 2023 – 2024 (EVEN Semester)

LAB MANUAL

FULLSTACK DEVELOPMENT (LABORATORY COMPONENT)


21CS62
VI Semester CS

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.

Vision and Mission of the Department


Vision
To become a leading department engaged in quality education and research in the field of
computer science and engineering.

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.

PROGRAM SPECIFIC OUTCOMES (PSOs)


PSO 1: Analyze, design, implement and test innovative application software systems to meet the
specified requirements.
PSO 2: Understand and use systems software packages.
PSO 3: Understand the organization and architecture of digital computers, embedded systems
and computer networks.

PROGRAM OUTCOMES (POs)

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
consideration.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis
of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant
to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.
SYLLABUS
FULLSTACK DEVELOPMENT (LABORATORY COMPONENT)
(Effective from the academic year 2023 -2024)
SEMESTER – VI

Course Code: 21CS62 CIE Marks: 50


Teaching Hours/Week (L:T:P: S): 3:0:2:0 SEE Marks: 50
Total Hours of Pedagogy: 40T + 20P Total Marks: 100
Credits: 04 Exam Hours: 03

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.

b) Visual Studio Code:


1. Download and install Visual Studio Code from https://code.visualstudio.com/download.
2. Install the Python extension for code completion and debugging within VS Code.

Dept. of CSE, Vemana IT 1


Fullstack Development Laboratory 2023-24

Virtual Environment and Project Setup:


In command line type
py -3 -m venv <name_of_Virtual_Environment>
change directory to name_of_Virtual_Environment\scripts
activate

Update pip in the virtual environment by running the following command prompt:
python -m pip install --upgrade pip

Dept. of CSE, Vemana IT 2


Fullstack Development Laboratory 2023-24

Install Django in the virtual environment by running the following command


python -m pip install Django

Create the Django project

1. Create a folder called Djangoprojects.


2. Open visual studio
3. Open the folder Djangoprojects
4. Click File → Preferences → Extensions or (Ctrl+Shift+x)
5. Type python in search Extensions box
6. If Python language support is not installed then click on Install button.
7. Click View and Terminal
8. By default powershell will be displayed change it to command prompt.
9. Enable the virtual environment created by changing directory to Scripts directory of virtual
environment and execute activate command.
10. Change directory to Djangoprojects
11. Create Django project use the following command

Dept. of CSE, Vemana IT 3


Fullstack Development Laboratory 2023-24

django-admin startproject webproject1

Observe the Explorer in VS code

12. Change directory to webproject1 and create Django app use the following command (A
project can have many apps)
python manage.py startapp app1

Dept. of CSE, Vemana IT 4


Fullstack Development Laboratory 2023-24

Observe the Explorer in VS code

Dept. of CSE, Vemana IT 5


Fullstack Development Laboratory 2023-24

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" ),]

Dept. of CSE, Vemana IT 6


Fullstack Development Laboratory 2023-24

Start the server using


Python manage.py runserver
Then request in browser

Program 2
Develo

Dept. of CSE, Vemana IT 7


Fullstack Development Laboratory 2023-24

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.

In settings.py of project folder add app2 to INSTALLED_APPS

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>

Dept. of CSE, Vemana IT 8


Fullstack Development Laboratory 2023-24

{% endfor %}
</ol>
</body>
</html>

Update views.py of app2 with following code


from django.shortcuts import render
# Develop a simple Django app that displays an unordered list of fruits and ordered list of
# selected students for an event
def display_fruits_students(request):
fruits = ['Banana','Mango','Grapes','Water Melon']
students = ['Ananya','Brijesh','Deepa','Evangline','Fathima']
data = {'fruits':fruits,'students':students,'event':'Hackathon'}
return render(request,'fruits_students.html',{'data':data})

In urls.py of app2, add the following path to the urlpatterns list.


path('fruits/', views.display_fruits_students,name="display_fruits_students" ),

In urls.py of project add the following path to the urlpatterns list.


path('app2/', include('app2.urls')),

Output

Program 3

Dept. of CSE, Vemana IT 9


Fullstack Development Laboratory 2023-24

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.

In settings.py of project folder add app2 to INSTALLED_APPS

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;

Dept. of CSE, Vemana IT 10


Fullstack Development Laboratory 2023-24

}
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>&copy; 2024 My Website. All rights reserved. </p>
<p>Developed by Vemana IT</p>
</footer>
</body>
</html>

Dept. of CSE, Vemana IT 11


Fullstack Development Laboratory 2023-24

Create a HTML home.html file inside app3/templates folder.

{% 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 %}

Create a HTML about_us.html file inside app3/templates folder.

{% 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

Dept. of CSE, Vemana IT 12


Fullstack Development Laboratory 2023-24

community service initiatives that foster holistic development.</p>


{% endblock %}

Create a HTML contactus_us.html file inside app3/templates folder.


{% extends 'layout.html' %}
{% block title %}Contact Us{% endblock %}
{% block content %}
<h1>Get in Touch</h1>
<p>For admissions and inquiries, reach out to us at:</p>
<ul>
<li><strong>Email:</strong> [email protected]</li>
<li><strong>Phone:</strong> +91 63617 50682/683/686</li>
</ul>
<h1>Visit Our Campus</h1>
<p> VEMANA INSTITUTE OF TECHNOLOGY</p>
<p> #1 Mahayogi Vemana Road, 3rd Block, Kormangala,</p>
<p> Bengaluru - 560 034. </p>
<p>We welcome you to be a part of our thriving community that's dedicated to creating a better
tomorrow through technology and innovation.</p>
{% endblock %}

Update views.py of app3 with following code


from django.shortcuts import render
# Create your views here.
def home(request):
return render(request,"home.html")
def about_us(request):
return render(request,"about_us.html")
def contact_us(request):
return render(request,"contact_us.html")

In urls.py of app3, add the following path to the urlpatterns list.


path('home/', views.home,name="home" ),

Dept. of CSE, Vemana IT 13


Fullstack Development Laboratory 2023-24

path('about_us/', views.about_us,name="about_us" ),
path('contact_us/', views.contact_us,name="contact_us" ),

In urls.py of project add the following path to the urlpatterns list.


path('app3/', include('app3.urls')),

Output

Dept. of CSE, Vemana IT 14


Fullstack Development Laboratory 2023-24

Dept. of CSE, Vemana IT 15


Fullstack Development Laboratory 2023-24

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.

In settings.py of project folder add app4 to INSTALLED_APPS

In urls.py of project add the following path to the urlpatterns list.

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.

<!-- mylayout.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;

Dept. of CSE, Vemana IT 16


Fullstack Development Laboratory 2023-24

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>

Dept. of CSE, Vemana IT 17


Fullstack Development Laboratory 2023-24

</ul>
</nav>
</header>
<main>
{% block content %}
{% endblock %}
</main>
<footer>
<p>&copy; 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 %}

Dept. of CSE, Vemana IT 18


Fullstack Development Laboratory 2023-24

<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>

Dept. of CSE, Vemana IT 19


Fullstack Development Laboratory 2023-24

<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 %}

Dept. of CSE, Vemana IT 20


Fullstack Development Laboratory 2023-24

<h1>Students Registered for {{ course.name }}</h1>


<ul class="list-group">
{% for student in students %}
<li class="list-group-item">{{ student.name }}</li>
{% empty %}
<li class="list-group-item">No students registered for this course.</li>
{% endfor %}
</ul>
{% endblock %}
------------------------------------------------------------------------------------------------------------------------------------

#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

Dept. of CSE, Vemana IT 21


Fullstack Development Laboratory 2023-24

------------------------------------------------------------------------------------------------------------------------------------

#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

Dept. of CSE, Vemana IT 22


Fullstack Development Laboratory 2023-24

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

Dept. of CSE, Vemana IT 23


Fullstack Development Laboratory 2023-24

course = get_object_or_404(Course, pk=course_id)


student = Student.objects.filter(name=student_name).first()
if not student:
# If the student does not exist, return an error message
return render(request, 'register_student.html', {'courses':
Course.objects.all(), 'error_message': 'Student does not exist in the database.'})
# Add the student to the course
course.students.add(student)
return render(request, 'confirmation.html', {'message': "Student Registered Successfully..."})

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})

def students_list(request, course_id):


# Retrieve the course based on course_id or return 404 if not found
course = get_object_or_404(Course, course_id=course_id)
# Retrieve the students associated with the course
students = course.students.all()
return render(request, 'students_list.html', {'course': course, 'students': students})

Output

Dept. of CSE, Vemana IT 24


Fullstack Development Laboratory 2023-24

Dept. of CSE, Vemana IT 25


Fullstack Development Laboratory 2023-24

Dept. of CSE, Vemana IT 26


Fullstack Development Laboratory 2023-24

Dept. of CSE, Vemana IT 27


Fullstack Development Laboratory 2023-24

Dept. of CSE, Vemana IT 28


Fullstack Development Laboratory 2023-24

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.

Modify the files which was created in Program 4

# 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

Dept. of CSE, Vemana IT 29


Fullstack Development Laboratory 2023-24

After login we can Add Student or Course

Note the output for


 Student insertion
 Student modification
 Student listing
 Student deletion
 Course insertion

Dept. of CSE, Vemana IT 30


Fullstack Development Laboratory 2023-24

 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.

Modify the files which was created in Program 5

Add the following line to mylayout.html, after Courses list element


<!-- mylayout.html -->
<li><a href="{% url 'register_proj' %}">Register Project</a></li>

<!-- project_reg.html -->


{% extends 'mylayout.html' %}
{% block title %} Project Details Registration {% endblock %}
{% block content %}
<form method="POST" action="">
{% csrf_token %}
<table >
{{ form.as_table }}
<tr>
<td>
<input type="submit" value="Add Project"/>
</td>
</tr>
</table>
</form>
{% endblock %}

<!-- student_details.html -->


{% extends 'mylayout.html' %}
{% block title %}Student Details{% endblock %}
{% block content %}
<h1>Student Details</h1>

Dept. of CSE, Vemana IT 31


Fullstack Development Laboratory 2023-24

{% 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 %}

In students_list.html change the following line.


<li class="list-group-item"><a href="{% url 'students_details' student.id
%}">{{ student.name }} </a> </li>

Dept. of CSE, Vemana IT 32


Fullstack Development Laboratory 2023-24

# 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

Dept. of CSE, Vemana IT 33


Fullstack Development Laboratory 2023-24

Dept. of CSE, Vemana IT 34


Fullstack Development Laboratory 2023-24

Dept. of CSE, Vemana IT 35


Fullstack Development Laboratory 2023-24

Dept. of CSE, Vemana IT 36

You might also like