FullStack Development Manual
FullStack Development Manual
VI- Semester
Prepared by
Prof. Pavithra
N Prof. Ambika
S
VISION
To create and disseminate knowledge to meet the needs of IT industry and community at
large and foster the students in the skills and passion to contribute and engage with the
world.
MISSION
Global outlook and action, offering our faculty and students a global passport to learn and
work.
Urbanizing in orientation and creativity, reflecting and shaping the society of the
21st century.
Integrating the different talents of students in multi-disciplinary team approach with
project focus and management.
Preparing students for professions of the future.
Training and monitoring the faculty and students through in-house talent for research.
PO 2: Design and develop a system, component or process to meet the desired needs within the
realistic constraints to solve the real-time problems for betterment of society.
PO 5: Use the techniques, skills and modern engineering tools necessary for engineering
practice.
PO 10: Adapt to any working environment of heterogeneous and multidisciplinary teams with
good sustainability and high performance.
PO 11: Clear successfully the competitive exams for placement, higher studies and government
services.
PO 12: Understand and demonstrate the impact of engineering solutions in a global, economic,
environmental and societal context.
PSO 1: An ability to design and develop hardware and software in emerging technology
environments like cloud computing embedded products and real-time systems. (Orientation
towards Systems Programming).
PSO 2: Knowledge of data management system like data acquisition, big data so as to enable
students in solving problems using the techniques of data analytics like pattern recognition and
knowledge discovery. (Orientation towards Data Sciences).
CLO 2. Make use of rapid application development in the design of responsive web pages.
CLO 3. Illustrate Models, Views and Templates with their connectivity in Django for full stack
web development.
CLO 4. Demonstrate the use of state management and admin interfaces automation in Django.
CLO 5. Design and implement Django apps containing dynamic pages with SQL databases.
CO 1. Understand the working of MVT based full stack web development with Django.
CO 3. Analyze the role of Template Inheritance and Generic views for developing full stack web
applications.
CO 4. Apply the Django framework libraries to render nonHTML contents like CSV and PDF.
CO 5. Perform jQuery based AJAX integration to Django Apps to build responsive full stack
web applications,
LIST OF PROGRAMS
Sl.
Name of Experiment
No.
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.
2. 1. Develop a simple Django app that displays an unordered list of fruits and ordered list
of selected students for an event
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.
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.
3. 1. For student and course models created in Lab experiment for Module2, register admin
interfaces, perform migrations and illustrate data entry through admin forms.
2. Develop a Model form for student that contains his topic chosen for project,
languages used and duration with a model called project.
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.
2. Develop example Django app that performs CSV and PDF generation for any models
created in previous laboratory component.
5. 1. Develop a registration page for student enrolment as done in Module 2 but without
page refresh using AJAX.
2. Develop a search application in Django using AJAX that displays courses enrolled by
a student being searched.
Full Stack Development refers to the practice of developing both the front-end (client
side) and back-end (server-side) portions of web applications.
A full stack developer is proficient in working with both the front-end and back-end
technologies, allowing them to build complete web applications independently or as part
of a team.
Technologies used in full stack development.
Front-End Technologies:
Back-End Technologies:
Server-side languages like JavaScript (Node.js), Python (Django, Flask), Ruby (Ruby on
Rails), Java (Spring Boot), or PHP (Laravel), C#(.Net Framework), java(Servlets)
Databases such as MySQL, PostgreSQL, MongoDB, or Firebase for storing and
managing data.
Web servers like Apache or Nginx or IIS or Tomcat or Caddy (with built in support for
https) for handling HTTP requests.
Why Django?
Rounded Solution
Great Exposure
Complete Ownership
Security (Prevention of threats such as SQL injection, cross-site scripting (XSS), cross site
request forgery (CSRF), and click jacking by providing {% csrf_token %} django tag to be
included inside the form.
This token generates a hidden input field containing a unique CSRF token. This token is
then validated by Django when the form is submitted, ensuring that the request originated from
the same site and protecting against CSRF attacks.
What is Django?
Django is a free and open source web application framework which offers fast and effective
dynamic website development.
Framework
A framework is a pre-built collection of libraries, modules, and tools that provides a structured
approach to developing software applications.
Django Evolution
3. Realize the application from step 1 shares much in common with the application from step 2.
4. Refactor the code so that application 1 shares code with application 2.
Django MVT
The MVT is a software design pattern which includes three important components Model, View
and Template.
The Model helps to handle database. It is a data access layer which handles the data.
The Template is a presentation layer which handles User Interface part completely.
The View is used to execute the business logic and interact with a model to carry data and
renders a template.
Characteristics of Django
Loosely Coupled − Django helps you to make each element of its stack independent of the
others.
Not repeated- Everything should be developed in precisely one place instead of repeating it
again
Consistent design - Django maintains a clean design and makes it easy to follow the best web
development practices.
A Python Virtual Environment is an isolated space where you can work on your Python
projects, separately from your system-installed Python.
You can set up your own libraries and dependencies without affecting the system Python.
It allows you to have multiple Python environments with different versions of Python and
different sets of installed packages on the same system.
It is generally good to have one new virtual environment for every Python-based project you
work on.
You can change the system python version, django version and other dependencies without
affecting the project python version, django versions and dependencies.
Creating system root folder, project root project folder, creating virtual env inside project
root folder.
Create a system root folder with the name BIT_CSE_FDP in the file system (inside any
preferred drive).
Create a project root folder inside BIT_CSE_FDP with the name “hello_world”
(assuming we are doing simple hello world program)
Run “code.” in the cmd prompt to launch the project folder “hello_world” in VS code.
or
Launch VS code from the task bar, goto file menu navigate and open “hello_world” Command
palette (select your venv as python interpreter for your project root folder)
Command palette (select your venv as python interpreter for your project root folder)
In VS Code, open the Command Palette (View > Command Palette or (Ctrl+Shift+P)). Then
select the Python: Select Interpreter command
The command presents a list of available interpreters that VS Code can locate automatically.
From the list, select the virtual environment in your project folder that starts with ./env or .\env:
Select the virtual environment that is created “hello_world_venv”. Look for recommended
Create the django project with the name “hello_world_proj” inside the project root folder
“hello_world”
SAMPLE PROGRAMS
1. Helloworld
views.py
from django.http import HttpResponse
from django. Shortcuts import render
def hello(request):
resp="<h1>Hello World!!!!</h1>”
urls.py
OUTPUT
2. GreetUser
views.py
from django.shortcuts import render
def greet(request,user):
uname=user
d={'user':user}
return render(request,'greet.html',d)
urls.py
from django.contrib import admin
from django.urls import path
greet.html
<!DOCTYPE html>
<html>
<head>
<title>Greet App</title>
</head>
<body>
<h1>{{user}} Good afternoon! Welcome to FDP on Full stack development</h1>
</body>
</html>
OUTPUT
LAB PROGRAMS
Experiment-01
1.1 Installation of Python, Django and Visual Studio code editors can be demonstrated.
Here are the steps you can follow to download Python: Steps to Download & Install Python
Now, Select Customize installation and proceed. We can also click on the customize installation
to choose desired location and features. Other important thing is installing launcher for the all
user must be checked.
The set-up is in progress. All the python libraries, packages, and other python default files will
be installed in our system. Once the installation is successful, the following page will appear
saying “Setup was successful ".
To verify whether the python is installed or not in our system, we have to do the following.
Now, to work on our first python program, we will go the interactive interpreter prompt (idle).
To open this, go to "Start" and type idle. Then, click on open to start working on idle.
Step – 1: Open Google and type Visual Studio Code download in the search bar.
Step – 3: Now, select the respective OS. In this case we are selecting Windows.
Step – 4: The file will be downloaded onto your system. Open the file and then click on
Install.
After downloading the VS Code file, the official site will display a Thanks message for
downloading the file.
Step – 6: Then it prompts for the file location, where you want to save the VS Code file.
Browse the location and then click on Next.
Step – 7: Next, you see the prompt for the additional task which we want the VS Code to
perform. At this step, choose the default settings and then click on next.
Step – 8: The next prompt is how you want the VS Code on your startup. Change
according to your convenience and click on Next.
Step – 10: At this step, we have completed installing VS Code, click on Finish.
Step – 11: Now that VS Code installation is successful, the page appears as below:
We can change the look as per our choice and continue working on it.
Here are the steps you can follow: Steps to Install Django
Experiment-02
Here are the steps you can follow to create virtual environment: Steps to Create Virtual
Environment, Django Project and App
In VS Code, go to File > Open... and create a new folder or select an existing folder where you
want to create your Django project.
In VS Code, go to View > Terminal or use the keyboard shortcut Ctrl+`` (Windows/Linux) or
Cmd+`' (macOS) to open the integrated terminal.
In the terminal, run the following command to create a new virtual environment:
Step-05: Install Django with the virtual environment active, install Django by running the
following command in the terminal: pip install django
[Replace myapp with the name you want to give to your app.]
In the VS Code file explorer, locate the settings.py file (usually located in the myproject
directory) and open it.
Locate the INSTALLED_APPS list and add the name of your new app to the list
after creating your Django app, the next step is to create database migrations for your app's
models (if you have any defined). Here's how you can do that using the python manage.py
makemigrations command in Visual Studio Code (VS Code)
Once you've reviewed the migration files and are ready to apply the changes to your database,
run the following command in the terminal:
Step-09: Run Your Project Here's how you can run the Django development server using the
python manage.py runserver command in Visual Studio Code (VS Code)
Check the server output the terminal will display the URL where the development server is
running, typically http://127.0.0.1:8000/. It will also show any startup logs or warnings, if any.
Open the development server in your browser Copy the URL from the terminal output (e.g.,
http://127.0.0.1:8000/) and paste it into your web browser's address bar.
Experiment-03
Develop a Django app that displays current date and time in server.
Step-01: This app will be created in the Django project we made earlier.
Locate the INSTALLED_APPS list and add the name of your new app to the list:
• Open the views.py file in your Django app's directory (e.g., datetimeapp/views.py).
• Create a new view function that will handle the request and render the date and time:
Views.py
def current_datetime(request):
now = datetime.datetime.now ()
context = {'datetime': now}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Current Date and Time</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet">
<style>
/* Center content vertically */
html, body {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div class="container text-center">
<h1>Current Date and Time on the Server</h1>
<p>{{ datetime }}</p>
</div>
<!-- Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></
script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]
alpha1/dist/js/bootstrap.min.js"></script>
</body>
</html>
This maps the current_datetime view function to the root URL (/).
Urls.py
OUTPUT
Experiment-04
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.
Step-01: This app will be created in the Django project we made earlier.
Locate the INSTALLED_APPS list and add the name of your new app to the list:
Views.py
from django.shortcuts import render
import datetime
from dateutil import tz
def datetime_offsets(request):
now = datetime.datetime.now()
context = {
'current_datetime': now,
'four_hours_ahead': now + datetime.timedelta(hours=4),
'four_hours_before': now - datetime.timedelta(hours=4),
}
return render(request, 'datetime_offsets.html', context)
Experiment-05
Develop a simple Django app that displays an unordered list of fruits and ordered list of selected
students for an event.
Step-01: This app will be created in the Django project we made earlier.
<style>
html, body {
height: 100%;
}
body
{ display:
flex;
justify-content: center;
align-items: center;
}
.container {
text-align: center;
}
/* Style for lists */
.list-container
{ display: inline-
block;
margin: 0 20px; /* Add space between lists */
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col">
<h1>Fruits</h1>
<ul class="list-group list-container">
{% for fruit in fruits %}
<li class="list-group-item">{{ fruit }}</li>
{% endfor %}
</ul>
</div>
<div class="col">
<h1>Selected Students</h1>
<ol class="list-group list-container">
{% for student in students %}
<li class="list-group-item">{{ student }}</li>
{% endfor %}
</ol>
</div>
</div>
</div>
<!-- Bootstrap JS (optional) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
OUTPUT
Experiment-06
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
Step-01: This app will be created in the Django project we made earlier.
Locate the INSTALLED_APPS list and add the name of your new app to the list:
color: #fff;
padding: 10px;
text-align: center; /* Center align header content */
}
nav ul {
list-style-type: none;
margin: 0;
padding: 0;
display: inline-block; /* Display nav items inline-block */
}
nav ul li
{ display:
inline;
margin-right: 10px;
}
nav ul li a
{ color: #fff;
}
text-decoration: none;
footer {
background-color: #333;
color: #fff;
padding: 10px;
text-align: center;
}
/* Center align content */
.content-wrapper {
display: flex;
justify-content: center;
align-items: center;
min-height: 80vh; /* Set minimum height for content area */
}
</style>
{% load static %}
</head>
<body>
<header>
<nav>
<ul>
<li><a href="{% url 'main' %}" style="text-decoration:none;">Home</a></li>
<li><a href="{% url 'about' %}" style="text-decoration:none;">About Us</a></li>
<li><a href="{% url 'contact' %}" style="text-decoration:none;">Contact Us</a></li>
</ul>
</nav>
</header>
Dept. of CS&E, SJMIT, Chitradurga Page 48
Fullstack Development (21CS62) 2023-24
<div class="content-wrapper">
{% block content %}
{% endblock %}
</div>
<footer>
<p>© 2024 Search Creators. Developed by Hanumanthu.</p>
</footer>
<!-- Include Bootstrap JS from CDN (Optional) -->
</body>
</html>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
home.html
{% extends 'portfolio/layout.html' %}
{% block title %}Home{% endblock %}
{% block extra_css %}
<!-- Include Bootstrap CSS from CDN -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
/* Custom CSS to center align content */
.center-content {
display: flex;
justify-content: center;
align-items: center;
height: 80vh; /* Set height to viewport height for full page centering */
}
.center-content > div
{ text-align: center;
}
</style>
{% endblock %}
{% block content %}
<div class="center-content">
<div>
<h1 class="text-center my-3">Welcome to My Website</h1>
<p class="text-center">This is the home page of our website.</p>
<img src="/static/images/1.webp" alt="images" class="img-fluid p-5" width="100%"
height="580">
</div>
</div>
{% endblock %}
{% block extra_js %}
<!-- Include Bootstrap JS from CDN (Optional) -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
{% endblock %}
about.html
{% extends 'portfolio/layout.html' %}
{% block title %}About Us{% endblock %}
{% block extra_css %}
<!-- Include Bootstrap CSS from CDN -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
{% endblock %}
{% block content %}
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<h1 class="text-center">About Us</h1>
<p class="text-center">We are a company that provides awesome products and
services.</p>
</div>
</div>
<!-- Service Images -->
<div class="row justify-content-center mt-5">
<div class="col-md-3 text-center">
<img src="/static/images/1.webp" alt="Service 1" class="img-fluid">
<p>Web Development</p>
</div>
<div class="col-md-3 text-center">
<img src="/static/images/2.jpeg" alt="Service 2" class="img-fluid">
<p>Boost Your Skill With ChatGPT</p>
</div>
<!-- Add more service images here -->
</div>
</div>
{% endblock %}
{% block extra_js %}
<!-- Include Bootstrap JS from CDN (Optional) -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
{% endblock %}
contact.html
{% extends 'portfolio/layout.html' %}
{% block title %}Contact Us{% endblock %}
{% block extra_css %}
<!-- Include Bootstrap CSS from CDN -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
{% endblock %}
{% block content %}
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<h1 class="text-center">Contact Us</h1>
<p class="text-center">You can reach us at:</p>
<ul class="list-unstyled">
<li class="text-center">Email: [email protected]</li>
<li class="text-center">Phone: 123-456-7890</li>
<li class="text-center">Address: 123 Main Street, City, State</li>
</ul>
</div>
</div>
</div>
{% endblock %}
{% block extra_js %}
<!-- Include Bootstrap JS from CDN (Optional) -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
{% endblock %}
portfolioapp/views.py
fullstack_project/urls.py
Final Output by Clicking Above Navbar Home, About Us, Contact Us Buttons
Experiment-07
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.
Step-01: This app will be created in the Django project we made earlier.
admin.site.register(Course)
admin.site.register(Student)
forms.py
class CourseForm(forms.ModelForm):
class Meta:
model = Course
fields = ['name', 'description']
widgets = {
'form-select',
'name': forms.TextInput(attrs={'class': 'form-control'}),
'description': forms.Textarea(attrs={'class': 'form-control', 'rows':
3}),
}
Views.py
if request.method == 'POST':
form = CourseForm(request.POST)
if form.is_valid():
form.save()
return redirect('index')
else:
form = CourseForm()
return render(request, 'registration/register_course.html', {'form': form})
def student_list(request, course_id):
course = Course.objects.get(id=course_id)
students = course.students.all()
return render(request, 'registration/student_list.html', {'students': students, 'course': course})
register_student.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Registration</title>
<!-- Bootstrap CSS -->
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Register Student</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
<!-- Bootstrap JavaScript (Optional) -->
<script
src="https://cdn.jsdelivr.net/npm/[email protected]
alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Example JavaScript to initialize the dropdown
<!-- Your custom JavaScript to initialize the dropdown (Optional) -->
var dropdownElementList = [].slice.call(document.querySelectorAll('.dropdown-toggle'))
var dropdownList = dropdownElementList.map(function (dropdownToggleEl) {
return new bootstrap.Dropdown(dropdownToggleEl)
});
</script>
</body>
</html>
register_course.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<h1>Register Course</h1>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<form method="post">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
{{ field.label_tag }}
{{ field }}
{% if field.help_text %}
<small class="form-text text-muted">{{ field.help_text }}</small>
{% endif %}
{% for error in field.errors %}
student_list.html
{% extends 'base.html' %}
{% block content %}
<h1>Students Registered for {{course.name}}</h1>
<ul>
{% for student in students %}
{% endfor %}
</ul>
{% endblock %}
<li>{{ student.first_name }} {{ student.last_name }}</li>
Step-10: Make Migration for check Models saved or not into the database
OUTPUT
Experiment-08
For student and course models created in Lab experiment for Module2, register admin interfaces,
perform migrations and illustrate data entry through admin forms.
Step-01: Register models in the admin site
from django.contrib import admin
from .models import Course, Student
@admin.register(Course)
class CourseAdmin(admin.ModelAdmin):
list_display = ('name', 'description')
@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'email')
filter_horizontal = ('courses',)
Experiment-09
Develop a Model form for student that contains his topic chosen for project, languages used and
duration with a model called project.
Step 1: Use an existing app i.e. student_course_registration_app
Step 2: Open the models.py file in the projects app and define the Project model.
models.py
class Project(models.Model):
topic = models.CharField(max_length=100, default='') # Added default value for topic
languages_used = models.CharField(max_length=100, default='')
duration = models.IntegerField(default=0)
def str (self):
return self.topic
Step 3: Create and apply migrations to create the necessary database tables.
python manage.py makemigrations
Step 4: Create a forms.py file in the projects app and define a ProjectForm based on the
Project model.
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ('topic', 'languages_used', 'duration')
widgets = {
'topic': forms.TextInput(attrs={'class': 'form-control'}),
'languages_used': forms.TextInput(attrs={'class': 'form-control'}),
'duration': forms.TextInput(attrs={'class': 'form-control'}),
Step 5: In views.py view function, import the ProjectForm and handle the form submission.
views.py view function
from .forms import ProjectForm
def register_project(request):
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
project = form.save()
# Redirect to a success page or another view
return redirect('index')
#return redirect('project_detail', project_id=project.pk)
else:
form = ProjectForm()
return render(request, 'registration/register_project.html', {'form': form})
Step 6: In views.py index function, add the projects Objects for Displaying the Register
Projects .
def index(request):
courses = Course.objects.all()
projects = Project.objects.all()
return render(request, 'registration/index.html',
{ 'courses': courses,
'projects': projects,
})
Step 9: Add a URL pattern for the register_project in your urls.py file
path('projects_register/', views.register_project, name='register_project'),
Experiment-10
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.
Step-1: First, let's create models for Student and Course if you haven't already:
Models.py
class Student(models.Model):
first_name = models.CharField(max_length=255, default='')
last_name = models.CharField(max_length=255, default='')
email = models.EmailField(unique=True, default='')
Step-2: Next, create views for the list and detail views and import necessary packages:
from django.views.generic import ListView, DetailView
class StudentListView(ListView):
model = Student
template_name = 'registration/stu_list.html'
context_object_name = 'students'
class StudentDetailView(DetailView):
model = Student
template_name = 'registration/student_detail.html'
context_object_name = 'student'
student_detail.html
{% extends 'base.html' %}
{% block content %}
<div class="container my-5">
<div class="row">
<div class="col-md-6 offset-md-3">
<div class="card">
<div class="card-body">
<h1 class="card-title"> Name: {{ student.first_name }} {{ student.last_name }}</h1>
<h1 class="card-title">Email: {{ student.email }}</h1>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
OUTPUT
Experiment-11
Develop example Django app that performs CSV and PDF generation for any models created in
previous laboratory component.
Step-01: This app will be created in the Django project we made earlier.
return self.title
Step-04: Create a views.py file in your books app and define the views for generating CSV
and PDF files
import csv
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
from .models import Book
def export_books_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="books.csv"'
writer = csv.writer(response)
writer.writerow(['Title', 'Author', 'Publication Date'])
for book in books:
writer.writerow(book)
return response
books = Book.objects.all().values_list('title', 'author', 'publication_date')
def export_books_pdf(request):
books = Book.objects.all()
template_path = 'book_list.html'
context = {'books': books}
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment;
filename="books.pdf"' template = get_template(template_path)
html = template.render(context)
pisa_status = pisa.CreatePDF(
html, dest=response)
if pisa_status.err:
return HttpResponse('We had some errors <pre>' + html + '</pre>')
return response
Step-04: In your books app, create a templates directory and an html file for rendering the
PDF.
books/
templates/
books/
book_list.html
book_list.html
<!DOCTYPE html>
<html>
<head>
<title>Book List</title>
<style>
body {
font-family: Arial, sans-serif;
}
table {
border-collapse: collapse;
width: 100%;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
</style>
</head>
<body>
<h1>Book List</h1>
<table>
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Publication Date</th>
</tr>
</thead>
<tbody>
{% for book in books %}
<tr>
<td>{{ book.title }}</td>
<td>{{ book.author }}</td>
<td>{{ book.publication_date }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
Step-07: Create the book titles and author and publication date
Run the following command to create a new data migration
python manage.py makemigrations books –empty
Book.objects.bulk_create([
python create_book_data.py
Experiment-12
Develop a registration page for student enrolment as done in Module 2 but without page refresh
using AJAX.
Step-01: This app will be created in the Django project we made earlier.
models.py
from django.db import models
# Create your models here.
class Student(models.Model):
first_name = models.CharField(max_length=255, default='')
last_name = models.CharField(max_length=255, default='')
email = models.EmailField(unique=True, default='')
Step-04: Create a views.py file in your app and define the views
Views.py
from django.shortcuts import render, redirect
from django.http import JsonResponse
from .forms import StudentForm
def student(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
student = form.save()
# You can perform additional operations here, like sending an email, etc.
return JsonResponse({'success': True})
else:
form = StudentForm()
return render(request, 'register_student.html', {'form': form})
Step-05: Create a forms.py file in your app and define the forms
from django import forms
from .models import Student
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['first_name', 'last_name', 'email']
widgets = {
'first_name': forms.TextInput(attrs={'class': 'form-control'}),
'last_name': forms.TextInput(attrs={'class': 'form-control'}),
'email': forms.EmailInput(attrs={'class': 'form-control'}),
}
Experiment-13
Develop a search application in Django using AJAX that displays courses enrolled by astudent
being searched.
Step-01: Use an existing app i.e. student_course_registration_app
<!DOCTYPE html>
<html>
<head>
<title>Search Students</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$.ajaxSetup({ hea
ders: {
'X-CSRFToken': '{{ csrf_token }}'
}
});
$(document).ready(function() {
$('#search-input').on('input', function() {
});
});
</script>
</head>
<body>
{% csrf_token %}
<div class="container">
<h1>Search Students</h1>
</div>
</body>
Step-04: Make migrations and migrate if any changes are made in your application eg.
Models etc..