21CS62 Fullstack Django Lab Manuals Search Creators (1)
21CS62 Fullstack Django Lab Manuals Search Creators (1)
Laboratory Components
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.
5. Develop a simple Django app that displays an unordered list of fruits and ordered list
of selected students for an event.
6. 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.
7. 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.
8. For student and course models created in Lab experiment for Module2, register admin
interfaces, perform migrations and illustrate data entry through admin forms.
9. Develop a model form for student that contains his topic chosen for project, languages
used and duration with a model called project.
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.
11. Develop example Django app that performs CSV and PDF generation for any models
created in previous laboratory component.
12. Develop a registration page for student enrolment as done in Module 2 but without page
refresh using AJAX.
13. Develop a search application in Django using AJAX that displays courses enrolled by
a student being searched.
Experiment-01
Installation of Python, Django and Visual Studio code editors can be demonstrated.
Python
Here are the steps you can follow to download Python: Steps to Download & Install Python
If in case you want to download the specific version of Python. Then, you can scroll down further
below to see different versions from 2 and 3 respectively. Click on download button right next to
the version number you want to download.
The following window will open. Click on the Add Path check box, it will set the Python path
automatically.
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.
Here are the steps you can follow: Steps to Download & Install VS Code
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
Creation of virtual environment, Django project and App should be demonstrated.
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:
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:
Here's how you can run the Django development server using the python manage.py runserver
command in Visual Studio Code (VS Code)
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).
• Import the necessary modules at the top of the file
• Create a new view function that will handle the request and render the date and time:
def current_datetime(request):
now = datetime.datetime.now ()
• In your app's directory (e.g., datetimeapp), create a new folder named templates.
• Inside the templates folder, create another folder with the same name as your app (e.g.,
myapp).
• Inside the datetimeapp folder, create a new file named current_datetime.html.
• Open current_datetime.html and add the following code to display the current date and
time:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet">
<style>
html, body {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
</style>
</head>
<body>
</div>
<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>
• Open the urls.py file in your Django app's directory (e.g., datetimeapp/urls.py).
• Import the view function at the top of the file
• Add a new URL pattern to the urlpatterns list
urlpatterns = [
This maps the current_datetime view function to the root URL (/).
• This includes the URL patterns from your app's urls.py file.
• In the VS Code terminal, navigate to your Django project's directory (the one containing
manage.py).
• Run the development server
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:
import datetime
def datetime_offsets(request):
now = datetime.datetime.now()
context = {
'current_datetime': now,
• This view function gets the current date and time using datetime.datetime.now(),
calculates the date and time four hours ahead and four hours before using
datetime.timedelta, and then passes all three values to the template as context variables.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet">
<style>
html, body {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
</style>
</head>
<body>
</div>
<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>
• Open the urls.py file in your Django app's directory (e.g., fourdate_timeapp/urls.py).
• Import the view function at the top of the file
• Add a new URL pattern to the urlpatterns list
urlpatterns = [
path('', include('fourdate_timeapp.urls')),
• This includes the URL patterns from your app's urls.py file.
• In the VS Code terminal, navigate to your Django project's directory (the one containing
manage.py).
• Run the development server
Experiment-05
Develop a simple Django app that displays an unordered list of fruits and ordered list of
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:
def home(request):
fruits = ['Apple', 'Banana', 'Orange', 'Mango', 'Pineapple']
students = ['John', 'Jane', 'Mike', 'Sarah', 'Tom']
context = {
'fruits': fruits,
'students': students,
}
return render(request, 'home.html', context)
• Here, we define a view function home that creates two lists: fruits and students. These
lists are then passed to the template as a context dictionary.
• In your app's directory (e.g., listfruitapp), create a new folder named templates (if it
doesn't already exist).
• Inside the templates folder, create another folder with the same name as your app (e.g.,
listfruitapp).
• Inside the fourdate_timeapp folder, create a new file named home.html.
• Open home.html and add the following code.
<!DOCTYPE html>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
rel="stylesheet">
<style>
html, body {
height: 100%;
body {
display: flex;
justify-content: center;
align-items: center;
.container {
text-align: center;
.list-container {
display: inline-block;
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col">
<h1>Fruits</h1>
{% endfor %}
</ul>
</div>
<div class="col">
<h1>Selected Students</h1>
{% endfor %}
</ol>
</div>
</div>
</div>
<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>
• In this template, we use Django's template tags to loop through the fruits and students
lists and render them as an unordered list and an ordered list, respectively.
• Open the urls.py file in your Django app's directory (e.g., listfruitapp/urls.py).
• Import the view function at the top of the file
• Add a new URL pattern to the urlpatterns list
urlpatterns = [
path('', include(listfruitapp.urls')),
• This includes the URL patterns from your app's urls.py file.
• In the VS Code terminal, navigate to your Django project's directory (the one containing
manage.py).
• Run the development server
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
pages: contact us, About Us and Home page of any website.
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:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
body {
margin: 0;
padding: 0;
header {
background-color: #333;
color: #fff;
padding: 10px;
nav ul {
list-style-type: none;
margin: 0;
padding: 0;
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;
.content-wrapper {
display: flex;
justify-content: center;
align-items: center;
</style>
{% load static %}
</head>
<body>
<header>
<nav>
<ul>
</ul>
</nav>
</header>
<div class="content-wrapper">
{% block content %}
{% endblock %}
</div>
<footer>
</footer>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
home.html
{% extends 'portfolio/layout.html' %}
{% block extra_css %}
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.center-content {
display: flex;
justify-content: center;
align-items: center;
height: 80vh; /* Set height to viewport height for full page centering */
text-align: center;
</style>
{% endblock %}
{% block content %}
<div class="center-content">
<div>
</div>
</div>
{% endblock %}
{% block extra_js %}
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
{% endblock %}
about.html
{% extends 'portfolio/layout.html' %}
{% block extra_css %}
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
{% endblock %}
{% block content %}
<div class="container">
<div class="col-md-8">
</div>
</div>
<p>Web Development</p>
</div>
</div>
</div>
</div>
{% endblock %}
{% block extra_js %}
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
{% endblock %}
contact.html
{% extends 'portfolio/layout.html' %}
{% block extra_css %}
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
{% endblock %}
{% block content %}
<div class="container">
<div class="col-md-6">
<ul class="list-unstyled">
</ul>
</div>
</div>
</div>
{% endblock %}
{% block extra_js %}
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
{% endblock %}
def main(request):
def about(request):
def contact(request):
• Open the urls.py file in your Django app's directory (e.g., listfruitapp/urls.py).
• Import the view function at the top of the file
• Add a new URL pattern to the urlpatterns list
urlpatterns = [
path('', include(portfolioapp.urls')),
• This includes the URL patterns from your app's urls.py file.
• In the VS Code terminal, navigate to your Django project's directory (the one containing
manage.py).
• Run the development server
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.
Locate the INSTALLED_APPS list and add the name of your new app to the list:
• Open the models.py file inside the student_course_registration_app and define your
models:
class Course(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Student(models.Model):
def __str__(self):
• Open the admin.py file inside the student_course_registration_app and register your
models:
admin.site.register(Course)
admin.site.register(Student)
• Create a new file called forms.py inside the student_course_registration_app and define
your forms:
class StudentForm(forms.ModelForm):
class Meta:
model = Student
widgets = {
class CourseForm(forms.ModelForm):
class Meta:
model = Course
widgets = {
Open the views.py file inside the student_course_registration_app and define your views:
def index(request):
courses = Course.objects.all()
def register_student(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()
return redirect('index')
else:
form = StudentForm()
def register_course(request):
if request.method == 'POST':
form = CourseForm(request.POST)
if form.is_valid():
form.save()
return redirect('index')
else:
form = CourseForm()
course = Course.objects.get(id=course_id)
students = course.students.all()
index.html
{% extends 'base.html' %}
{% block content %}
<div class="container">
<h1 class="mt-5">Courses</h1>
{% endfor %}
</ul>
</div>
{% endblock %}
register_student.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Registration</title>
<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 }}
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]
alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script>
});
</script>
</body>
</html>
register_course.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<h1>Register Course</h1>
<div class="container">
<div class="col-md-6">
<form method="post">
{% csrf_token %}
<div class="form-group">
{{ field.label_tag }}
{{ field }}
{% if field.help_text %}
{% endif %}
{% endfor %}
</div>
{% endfor %}
</form>
</div>
</div>
</div>
{% endblock %}
student_list.html
{% extends 'base.html' %}
{% block content %}
<ul>
{% endfor %}
</ul>
{% endblock %}
• Create a base.html file inside the templates directory with the following content:
base.html
<!DOCTYPE html>
<html>
<head>
<title>Student Registration</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
• Open the urls.py file inside your student_course_registration_app and define your URLs:
urlpatterns = [
• Open the urls.py file inside your project and include the URLs from the
student_course_registration_app:
Step-10: Make Migration for check Models saved or not into the database
• In the VS Code terminal, navigate to your Django project's directory (the one containing
manage.py).
• Run the development server
Fig: Students Register Particular Courses Screen [You can Check as You Register
Courses]
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.
@admin.register(Course)
class CourseAdmin(admin.ModelAdmin):
@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
filter_horizontal = ('courses',)
• In this code, we've registered the Course and Student models with the Django admin site.
• We've also specified the fields to be displayed in the list view for each model using the
list_display attribute.
• For the StudentAdmin class, we've added the filter_horizontal attribute to display the
courses field (which is a many-to-many relationship) as a horizontal filter in the admin
interface.
• If you haven't already created a superuser for your project, you'll need to do so to access
the admin interface.
• In your terminal or command prompt, run the following command
Password:1234 [For Simply but your wish to create your own username and password]
• Back in your web browser, enter the superuser credentials you just created and log in to
the admin interface.
Once you're logged in to the admin interface, you'll see the "Courses" and "Students" sections in
the left sidebar. Click on "Courses" to add a new course.
You can repeat these steps to add more courses and students through the admin interface.
Additionally, you can view, edit, and delete existing courses and students from the admin
interface.
Final Output
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 2: Open the models.py file in the projects app and define the Project model.
class Project(models.Model):
duration = models.IntegerField(default=0)
def __str__(self):
return self.topic
Step 3: Create and apply migrations to create the necessary database tables.
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
widgets = {
Step 5: In views.py view function, import the ProjectForm and handle the form submission.
def register_project(request):
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
project = form.save()
return redirect('index')
else:
form = ProjectForm()
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()
'courses': courses,
'projects': projects,
})
{% extends 'base.html' %}
{% block content %}
<h1>Create Project</h1>
<form method="post">
{% csrf_token %}
<div class="form-group">
<label for="id_topic">Topic:</label>
{{ form.topic }}
</div>
<div class="form-group">
{{ form.languages_used }}
</div>
<div class="form-group">
<label for="id_duration">Duration:</label>
{{ form.duration }}
</div>
</form>
</div>
{% endblock %}
<li class="list-group-item">
</li>
{% endfor %}
</ul>
• Add the register_student.html to this is Student can Register the Created Project
<div class="form-group">
{{ form.project.label_tag }}
{{ form.project }}
{{ form.project.errors }}
</div>
Step 9: Add a URL pattern for the register_project in your urls.py file
• In the VS Code terminal, navigate to your Django project's directory (the one containing
manage.py).
• Run the development server
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='')
courses = models.ManyToManyField(Course, related_name='students',
blank=True)
project = models.ManyToManyField('Project', related_name='students',
blank=True)
Step-2: Next, create views for the list and detail views and import necessary packages:
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'
provided, it will return the students associated with that course; otherwise, it
will return all students.
stu_list.html
{% extends 'base.html' %}
{% block content %}
<h1>Students</h1>
<ul>
<li>
</li>
{% endfor %}
</ul>
{% endblock %}
student_detail.html
{% extends 'base.html' %}
{% block content %}
<div class="row">
<div class="card">
<div class="card-body">
</div>
</div>
</div>
</div>
</div>
{% endblock %}
Index.html
<li class="list-group-item">
</li>
{% endfor %}
</ul>
• In the VS Code terminal, navigate to your Django project's directory (the one containing
manage.py).
• Run the development server
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.
Locate the INSTALLED_APPS list and add the name of your new app to the list:
• Open the models.py file inside the student_course_registration_app and define your
models:
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
publication_date = models.DateField()
def __str__(self):
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
def export_books_csv(request):
response = HttpResponse(content_type='text/csv')
writer = csv.writer(response)
writer.writerow(book)
return response
def export_books_pdf(request):
books = Book.objects.all()
template_path = 'book_list.html'
response = HttpResponse(content_type='application/pdf')
template = get_template(template_path)
html = template.render(context)
pisa_status = pisa.CreatePDF(
html, dest=response)
if pisa_status.err:
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 {
table {
border-collapse: collapse;
width: 100%;
th, td {
padding: 8px;
text-align: left;
</style>
</head>
<body>
<h1>Book List</h1>
<table>
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Publication Date</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
urlpatterns = [
Step-07: Create the book titles and author and publication date
Django Shell
• If you just want to create some sample data for testing or development purposes, you can
run the code in the Django shell as shown in the previous example. This is a quick and
easy way to create objects interactively.
Data Migration
• If you want to include the book data as part of your project's initial data setup, you can
create a data migration. Here's how you can do it
• This will create a new empty migration file in the books/migrations/ directory.
• Open the newly created migration file (e.g., books/migrations/0002_auto_<...>.py) and
add the code to create the book objects in the operations list of the Migration class.
Book.objects.bulk_create([
])
class Migration(migrations.Migration):
dependencies = [
('books', '0001_initial'),
operations = [
migrations.RunPython(create_book_data),
• If you need to create the book data programmatically (e.g., during deployment or as part
of a data import process), you can create a custom Python script and run it as needed.
• Create a new Python file (e.g., create_book_data.py) in your project's root directory, and
add the code to create the book objects:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fullstack_project.settings')
import django
django.setup()
Book.objects.bulk_create([
])
python create_book_data.py
• Open the urls.py file inside your project and include the URLs from the book app:
• In the VS Code terminal, navigate to your Django project's directory (the one containing
manage.py).
• Run the development server
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.
Locate the INSTALLED_APPS list and add the name of your new app to the list:
• Open the models.py file inside the registration app and define your models:
class Student(models.Model):
Step-04: Create a views.py file in your app and define the views
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.
else:
form = StudentForm()
Step-05: Create a forms.py file in your app and define the forms
class StudentForm(forms.ModelForm):
class Meta:
model = Student
widgets = {
register_student.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Student Registration</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>Student Registration</h1>
{% csrf_token %}
<div class="form-group">
{{ field.label_tag }}
{{ field }}
{% if field.help_text %}
{% endif %}
{% endfor %}
</div>
{% endfor %}
</form>
<div id="response"></div>
</div>
<script>
$(document).ready(function() {
$('#student-form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: formData,
success: function(response) {
if (response.success) {
$('#student-form')[0].reset();
} else {
},
});
});
});
</script>
</body>
</html>
# project/urls.py
urlpatterns = [
• Open the urls.py file inside your project and include the URLs from the registration app:
• In the VS Code terminal, navigate to your Django project's directory (the one containing
manage.py).
• Run the development server
Experiment-13
Develop a search application in Django using AJAX that displays courses enrolled by a
student being searched.
def search_students(request):
if is_ajax:
students = Student.objects.filter(first_name__icontains=query) |
Student.objects.filter(last_name__icontains=query)
results = []
student_data = {
'id': student.id,
'email': student.email,
results.append(student_data)
Registration/search.html
{% load static %}
<!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({
headers: {
});
$(document).ready(function() {
$('#search-input').on('input', function() {
$.ajax({
data: {
'query': query
},
success: function(data) {
if (results.length > 0) {
html += '</li>';
html += '</ul>';
} else {
$('#search-results').html(html);
});
});
});
</script>
</head>
<body>
{% csrf_token %}
<div class="container">
<h1>Search Students</h1>
<div id="search-results"></div>
</div>
</body>
</html>
• Very important to add the all The necessary AJAX scripts we provided
• Open the urls.py file inside your app and include the URLs
Step-04: Makemigrations and migrate if any changes are made in your application eg.
Models etc..
• In the VS Code terminal, navigate to your Django project's directory (the one containing
manage.py).
• Run the development server