[go: up one dir, main page]

0% found this document useful (0 votes)
72 views56 pages

FSD Lab Manual

The document outlines a fullstack development laboratory component focusing on Django, including installation instructions, project setup, and app creation. It provides step-by-step guidance on creating Django projects and apps, managing views and URLs, and displaying dynamic content such as current date and time. Additionally, it covers database integration with models and templates for rendering data in web applications.

Uploaded by

sariyaanjum8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views56 pages

FSD Lab Manual

The document outlines a fullstack development laboratory component focusing on Django, including installation instructions, project setup, and app creation. It provides step-by-step guidance on creating Django projects and apps, managing views and URLs, and displaying dynamic content such as current date and time. Additionally, it covers database integration with models and templates for rendering data in web applications.

Uploaded by

sariyaanjum8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 56

FULLSTACK DEVELOPMENT (21CS62)

Module 1 : Laboratory Component

1. Installation of Python, Django and Visual Studio code editors can be


demonstrated.
Python download and installation Link:

https://www.python.org/downloads/

Visual Studio Code download and installation link:

https://code.visualstudio.com/

Django installation:
Open a command prompt and type following command:

pip install django


2. Creation of virtual environment, Django project and App should be
demonstrated Create a project inside the folder using:

Open a New Terminal: In Menu Terminal -> New Terminal option


Creating project:
1. Create a django project -

Type following command in the terminal opened:

django -admin startproject projectname

This startproject command assumes that the current folder is your project folder, and
creates the following within it:

• manage.py: The Django command-line administrative utility for the project. You run
administrative commands for the project using

python manage.py <command> [options].

• A subfolder named p which contains the following files:

o __init__.py: an empty file that tells Python that this folder is a Python
package.
o wsgi.py: an entry point for WSGI-compatible web servers to serve your
project. You typically leave this file as-is as it provides the hooks for
production web servers.
o settings.py: contains settings for Django project, which you modify in the
course of developing a web app.

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

o urls.py: contains a table of contents for the Django project, which you also
modify in the course of development.

2. To verify the Django project, make sure your virtual environment is activated, then
start Django's development server using the command python manage.py
runserver. The server runs on the default port 8000, and you see output like the
following output in the terminal window:
Verify server by typing: python manage.py runserver

When you run the server the first time, it creates a default SQLite database in the file
db.sqlite3, which is intended for development purposes but can be used in production for
low-volume web apps. Also, Django's built-in web server is intended only for local
development purposes. When you deploy to a web host, however, Django uses the host's web
server instead. The wsgi.py module in the Django project takes care of hooking into the
production servers.

If you want to use a different port than the default 8000, specify the port number on
the command line, such as python manage.py runserver 5000.

3. When you're done, close the browser window and stop the server in VS Code using
Ctrl+C as indicated in the terminal output window.

4. In the VS Code Terminal with your virtual environment activated, run the

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

administrative utility's startapp command in your project folder (where manage.py


resides):

python manage.py startapp appname

5. The command creates a folder by appname that contains a number of code files and
one subfolder. Of these, you frequently work with views.py (that contains the
functions that define pages in your web app) and models.py (that contains classes
defining your data objects). The migrations folder is used by Django's administrative
utility to manage database versions. There are also the files apps.py (app
configuration), admin.py (for creating an administrative interface), and tests.py (for
unit tests).

Demonstrations 1:
First create a project: django-admin startproject projectname

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Ex: django-admin startproject Module1

Create an app inside the project:


Go inside the created project file using:
PS C:\Users\User\OneDrive\Desktop\EXP1> cd Module1

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

PS C:\Users\User\OneDrive\Desktop\EXP1> python manage.py startapp program1 Before:

After:

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

PS C:\Users\User\OneDrive\Desktop\EXP1> python manage.py runserver


Before:

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

After:

Click on http://127.0.0.1:8000/

Now, go to settings.py under the project “Module1”

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Under the INSTALLED_APPS, add the app “program1”

Under the Module1, create the ‘views.py’

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Now, go the urls.py under the project “Module1”:

And add the content of line no. 19 and 23:

Note: Observe the error

Updated Code:

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

from django.contrib import admin


from sdjango.urls import path
from Module1.views import
hello_world
urlpatterns = [
path('admin/',
admin.site.urls),
path("hello/",hello_world)
]

Now, go the views.py under the project “Module1”:

And type the below content and observe the terminal now:
from django.http import HttpResponse
#definign a function which will receive the request and perform task pending upon function
#definition
def hello_world(request):
# This will return HelloWorld string as HttpResponse
return HttpResponse("Hello, Welcome to the Full Stack Development")

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Now, click on http://127.0.0.1:8000/

Demonstrations 2:

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Now, go to the urls.py in the project “Module1” and modify line no. 18 and 24 and observe
the terminal:

Now go the app “program1” and create the urls.py:

ow,
go to the views.py in the app “program1” and add the below contents:

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Now, go to the urls.py in the app “program1” and add the below contents:

Now, press ctrl+C, make sure the path is inside the created project and run the server and
click on http://127.0.0.1:8000/:
PS C:\Users\User\OneDrive\Desktop\EXP1\Module1> python manage.py runserver

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

3. Develop a Django app that displays current date and time in server. Now,
go the urls.py in the app “program1” and update the code:
Updated Code:
from django.contrib import admin
from django.urls import path,
include
from Module1.views import
hello_world

urlpatterns = [
path('admin/', admin.site.urls),
path("hello/",hello_world),
path('time/',include("program1.urls"
))
]

Now, go the views.py in the app “program1” and update the code:
Updated Code:
from django.shortcuts import render
from django.http import HttpResponse
import datetime

# Create your views here.

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

def index(reqest):
return HttpResponse("Starting
Program1")

def current_datetime(request):
now=datetime.datetime.now()
display=f"<html><body>Curre
nt Date and Time is
{now}.</body></html>"
return
HttpResponse(display)

Now, go to urls.py in the app “program1” and update the path content:
Updated Code:
from django.urls import path
from . import
views
urlpatterns= [

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

path('',views.current_datetime
)
]

Now, press ctrl+c, make sure the path is inside the created project and run the server and click
on http://127.0.0.1:8000/:
PS C:\Users\User\OneDrive\Desktop\EXP1\Module1> python manage.py runserver

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

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.

Now, create the second app called “program2” as follows:


Before:

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

After:

Go to settings.py under the project “Module1” Before:

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

After:
Add ‘program2’ under INSTALLED_APPS:

Now, go to urls.py under the project “Module1” and add the path:

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Now, go to views.py under the app “program2” and add the code:
Updated Code:

from django.shortcuts import render


from django.http import HttpResponse
import datetime

def offset_datetime(request):
sssnow =datetime.datetime.now()
four_hours_later = now + datetime.timedelta(hours=4)
four_hours_earlier = now - datetime.timedelta(hours=4)
display = f"<html><body>Current date and time: {now}<br>Four hours later:
{four_hours_later}<br>Four hours earlier:
{four_hours_earlier}</body></html>"
return HttpResponse(display)

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Now, create urls.py in the app “Program2” and add the below path:

Now run the server and click on http://127.0.0.1:8000/:


PS C:\Users\User\OneDrive\Desktop\EXP1\Module1> python manage.py runserver

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

***

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Module 2 : Laboratory Component

Program 1: Develop a simple Django app that displays an unordered list of fruits and
ordered list of selected students for an event.

Step1: Inside the project, create an app, as follows

Step2: Add the app ‘program3’ inside the settings.py:

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Step 3: Add the path inside the project urls.py:

urlpatterns = [
path('admin/', admin.site.urls),
path('program3/',include("program3.urls"))
]

Step 4: Now go to models.py inside the app:

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Step 5: Create the class in the models.py from


django.db import models

#views are connected to


models #models are
connected to DB # Create
your models here.
#if accessing the DB, then models needs to be
created class Student(models.Model):
#Student is a class name =
models.CharField(max_length=100)

def __str__(self): #self is the instance of the


Student return self.name

Step 6: Now go to views.py inside the app:

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Step 7: Create the views in the views.py

from django.shortcuts import render #Render will render the templet, here
it is html
from . models import Student #importing from the Student models.py

# Create your views here.


def display_list(request):
fruits=['Apple','Banana','Cherry','Dates']
students=Student.objects.all()
returnrender(request,'program3/display_list.html',
{'fruits':fruits,'studnets':students})
#return the render, here templet is display_list.html

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Select the Program3 and click on new folder icon and name it as templates
Again, select the templates and click on new folder icon and name it as program3 Again,
select the templates\program3 and click on the new file icon and name it as
display_list.html(Referthebelowimage)

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Write HTML program

<html>
<body>
<h1>Fruits</h1>
<u1>
{% for fruit in fruits %}
<li>{{fruit}}</li>
{% endfor %}
</u1>

<h1>Selected Students</h1>
<ol>
{% for student in studnets %}
<li>{{student.name}}</li>
{% endfor %}
</ol>
</body>
</html>

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Now, inside the Program3, create the urls.py:

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

from django.urls import path


from program3.views import display_list

urlpatterns=[
path('lists/',display_list),
]

Now, migrate
PS C:\Users\User\OneDrive\Desktop\FSD\FDP> python manage.py makemigrations

Now,

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

PS C:\Users\User\OneDrive\Desktop\FSD\FDP> python manage.py migrate

Now,
PS C:\Users\User\OneDrive\Desktop\FSD\FDP> python manage.py runserver

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Now,
http://127.0.0.1:8000/program3/lists/

It is not complete, because DB need to be explained

Now,
PS C:\Users\User\OneDrive\Desktop\FSD\FDP> python manage.py createsuperuser
And give username, email ID and password

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Go to admin.py under program3:

from django.contrib import admin


from .models import Student

# Register your models here.


admin.site.register(Student)

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Run the server now

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

127.0.0.1:8000/admin:

Click on +Add under Students in above

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

After adding, check under Students:

127.0.0.1:8000/progarm3/lists/:

Now, it is complete

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

1. Django App Displaying Lists of Fruits and Students

First, set up your Django models and views.

Step 1: Create Models

We don’t need models for fruits as they can be hardcoded, but let’s create
a model for students.

In `myapp/models.py`:

from django.db import models


class Student(models.Model):

name = models.CharField(max_length=100)
def __str__(self):
return self.name

Run the migrations:

python manage.py makemigrations


python manage.py migrate

Step 2: Create Views

In `myapp/views.py`:

from django.shortcuts import render


from .models import Student

def display_lists(request):
fruits = ['Apple', 'Banana', 'Cherry', 'Date']
students = Student.objects.all()
return render(request, 'myapp/display_lists.html', {'fruits': fruits,
'students': students})

Step 3: Create Templates

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

In `myapp/templates/myapp/display_lists.html`:

<html>
<body>
<h1>Fruits</h1>
<ul>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
</ul>

<h1>Selected Students</h1>
<ol>
{% for student in students %}
<li>{{ student.name }}</li>
{% endfor %}
</ol>
</body>
</html>

Update `myproject/urls.py`:

from django.urls import path


from myapp.views import display_lists

urlpatterns = [
path('lists/', display_lists),
]

2. Develop a Layout with Header, Footer, and Inherit Pages

Step 1: Create the Base Layout

In `myapp/templates/myapp/layout.html`:

<!DOCTYPE html>
<html lang="en">
<head>
MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR
FULLSTACK DEVELOPMENT (21CS62)

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about/">About Us</a></li>
<li><a href="/contact/">Contact Us</a></li>
</ul>
</nav>
</header>

{% block content %}
{% endblock %}

<footer>
<p>Copyright © Your Name 2022</p>
</footer>
</body>
</html>

Step 2: Create Inherited Pages

Create `home.html`, `about.html`, `contact.html` in `myapp/templates/myapp/`


directory inheriting from `layout.html`.
For example, `home.html`:
{% extends 'myapp/layout.html' %}

{% block content %}
<h1>Welcome to Our Site!</h1>
<p>This is the home page.</p>
{% endblock %}

Update `myproject/urls.py` to include paths for these new pages.

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

3. Django App for Student Registration

Step 1: Create Models

In `myapp/models.py`, add:

class Course(models.Model):
name = models.CharField(max_length=100)
students = models.ManyToManyField(Student)

def __str__(self):
return self.name

Step 2: Create Views for Registration and Display

In `myapp/views.py`, add functions to handle registration and list students in a


course:

from django.shortcuts import render, redirect


from .models import Course, Student

def register_student(request):
if request.method == 'POST':
student_name = request.POST.get('student_name')
course_id = request.POST.get('course_id')
student = Student.objects.create(name=student_name)
course = Course.objects.get(id=course_id)
course.students.add(student)
return redirect('course_detail', course_id=course.id)

courses = Course.objects.all()
return render(request, 'myapp/register_student.html', {'courses':
courses})

def course_detail(request, course_id):


course = Course.objects.get(id=course_id)
students = course.students.all()
return render(request, 'myapp/course_detail.html', {'course':
course, 'students': students})

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Step 3: Create Templates

Create `register_student.html` and `course_detail.html` to handle form


submissions and display course details, respectively.

register_student.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Register Student</title>
<!-- Bootstrap CSS for styling -->
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.
css">
</head>
<body>
<div class="container mt-5">
<h2>Register New Student to a Course</h2>
<form action="{% url 'program5:register_student' %}"
method="post">
{% csrf_token %}
<div class="mb-3">
<label for="student_name" class="form-label">Student
Name:</label>
<input type="text" class="form-control" id="student_name"
name="student_name" required>
</div>
<div class="mb-3">
<label for="course_id" class="form-label">Select
Course:</label>
<select class="form-select" id="course_id" name="course_id"
required>
{% for course in courses %}
<option value="{{ course.id }}">{{ course.name }}</option>
{% endfor %}
</select>

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

</div>
<button type="submit" class="btn
btn-primary">Register</button>
</form>

</div>

<!-- Bootstrap JS with Popper.js for interactive components -->


<script
src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.
min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js"
></script>
</body>
</html>

course_detail.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Course Details</title>
<!-- Bootstrap CSS -->
<linkrel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.
css">
</head>
<body>
<div class="container mt-5">
<h2>Course Details: {{ course.name }}</h2>
<div class="card">
<div class="card-body">
<h5 class="card-title">Course ID: {{ course.id }}</h5>
<p class="card-text">Enrolled Students:</p>

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

<ul class="list-group list-group-flush">


{% for student in course.students.all %}
<li class="list-group-item">{{ student.name }}</li>
{% empty %}
<li class="list-group-item">No students enrolled yet.</li>
{% endfor %}
</ul>
</div>
</div>
</div>

<!-- Bootstrap JS with Popper.js -->


<script
src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.
min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js"
></script>
</body>
</html>

Step 4: Update URLs

Update `myproject/urls.py` to include paths for registering students and


displaying course details.

Module 3 : Laboratory Component

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

1.Set up and customize the Django admin panel for Student and
Course models. Perform migrations and use the admin to manage data
entry.

Step 1: Define Models

First, ensure your Student and Course models are correctly defined in
models.py. For this exercise, we assume a ManyToMany relationship as set up
previously:

from django.db import models

class Course(models.Model):
name = models.CharField(max_length=100)
students = models.ManyToManyField('Student', related_name='courses')

def __str__(self):
return self.name

class Student(models.Model):
name = models.CharField(max_length=100)

def __str__(self):
return self.name

Step 2: Perform Migrations

Generate and apply migrations to create the necessary database schema:

python manage.py makemigrations


python manage.py migrate

Step 3: Register Models in Admin

Modify admin.py in your app directory to include your models in the Django
admin interface:
MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR
FULLSTACK DEVELOPMENT (21CS62)

from django.contrib import admin


from .models import Student, Course

admin.site.register(Student)
admin.site.register(Course)

Step 4: Customize Admin Interface

Optionally, you can customize how these models appear in the admin. For
example, add a more detailed configuration for Course:

class CourseAdmin(admin.ModelAdmin):
list_display = ('name', 'list_students')

def list_students(self, obj):


return ", ".join([student.name for student in obj.students.all()])

admin.site.register(Course, CourseAdmin)

2. Create a model form for the Student that includes fields for a project topic,
the programming languages used, and the duration of the project.

Step 1: Update the Student Model

First, let's add a Project model and connect it to the Student model in models.py:

class Project(models.Model):
topic = models.CharField(max_length=200)
languages = models.CharField(max_length=200)
duration = models.IntegerField(help_text="Duration in days")

def __str__(self):
return self.topic

class Student(models.Model):

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

name = models.CharField(max_length=100)
project = models.OneToOneField(Project, on_delete=models.SET_NULL,
null=True, blank=True)

def __str__(self):
return self.name

Perform migrations again after updating the models.

Step 2: Create a Model Form

Create a model form for Student in your forms.py file:

from django import forms


from .models import Student

class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['name', 'project']
widgets = {
'project': forms.HiddenInput(), # Initially hidden, set via another form or
view logic
}

Step 3: Use the Form in a View

Implement a view in views.py to handle this form:

from django.shortcuts import render, redirect


from .forms import StudentForm

def register_student(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()
return redirect('some-view-name')
else:
MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR
FULLSTACK DEVELOPMENT (21CS62)

form = StudentForm()
return render(request, 'your_template.html', {'form': form})

Step 4: Create Template

Create a template to display the form:

<!-- your_template.html -->


<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>

Module 4 : Laboratory Component

1. This program will demonstrate how to use Django's generic views


to display a list of students and the details for a selected student.

Step 1: Update URLs


MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR
FULLSTACK DEVELOPMENT (21CS62)

First, you will need to define the URL patterns that will route to the generic
views.

In myproject/urls.py, add the following:

from django.urls import path


from .views import StudentListView, StudentDetailView
urlpatterns = [
path('students/', StudentListView.as_view(), name='student-list'),
path('students/<int:pk>/', StudentDetailView.as_view(), name='student-
detail'),
]

Step 2: Define the Views

In myapp/views.py, import the necessary generic views and define


StudentListView and StudentDetailView.

from django.views.generic import ListView, DetailView


from .models import Student

class StudentListView(ListView):
model = Student
template_name = 'students/student_list.html'
context_object_name = 'students'

class StudentDetailView(DetailView):
model = Student
template_name = 'students/student_detail.html'
context_object_name = 'student'

Step 3: Create Templates

Create the templates for these views in myapp/templates/students/.


student_list.html:

<h2>Student List</h2>
<ul>
{% for student in students %}
<li><a href="{% url 'student-detail' pk=student.pk
%}">{{ student.name }}</a></li>
{% endfor %}
MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR
FULLSTACK DEVELOPMENT (21CS62)

</ul>

student_detail.html:

<h2>Student Details</h2>
<p>Name: {{ student.name }}</p>

2. This program will guide you on how to generate CSV and PDF
files for the Student model data.

Generating CSV Files

In myapp/views.py, add a view to generate a CSV file:

import csv
from django.http import HttpResponse
from .models import Student

def export_students_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="students.csv"'

writer = csv.writer(response)
writer.writerow(['Name'])

students = Student.objects.all().values_list('name')
for student in students:
writer.writerow(student)
return response

Update myproject/urls.py to include this view:

path('export/csv/', views.export_students_csv, name='export-students-csv'),

Generating PDF Files

Generating PDFs requires the ReportLab library, so ensure it is installed:

pip install reportlab

In myapp/views.py, add a view to generate a PDF file:

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

from reportlab.pdfgen import canvas


from django.http import HttpResponse

def export_students_pdf(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="students.pdf"'

p = canvas.Canvas(response)

students = Student.objects.all()
y = 800
for student in students:
p.drawString(100, y, f"Student Name: {student.name}")
y -= 40

p.showPage()
p.save()
return response

Update myproject/urls.py to include this PDF export view:

path('export/pdf/', views.export_students_pdf, name='export-students-


pdf'),

Module 5 : Laboratory Component

1. This program will guide you through creating a student registration


form that submits data to the server and processes responses without a
page refresh.

Step 1: Set Up Your Django Models

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

Assuming you have a Student model, ensure it is appropriate for registration


purposes:

from django.db import models

class Student(models.Model):
name = models.CharField(max_length=100)
# Add additional fields if necessary

def __str__(self):
return self.name

Step 2: Create a Django View to Handle AJAX

Create a view in views.py that handles the AJAX POST request:

from django.http import JsonResponse


from .models import Student
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def register_student(request):
if request.method == 'POST':
name = request.POST.get('name')
Student.objects.create(name=name)
return JsonResponse({"message": "Student Registered Successfully"},
status=200)
return JsonResponse({"error": "Something went wrong"}, status=400)

Step 3: Create the Registration Form and AJAX Script

In your Django template (register_student.html), set up the form and include


jQuery to handle the AJAX:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Register Student</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></
script>
</head>
<body>
MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR
FULLSTACK DEVELOPMENT (21CS62)

<form id="studentForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Register</button>
</form>

<script>
$(document).ready(function() {
$('#studentForm').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "register_student" %}',
data: {
'name': $('#name').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
success: function(response) {
alert(response.message);
$('#studentForm')[0].reset();
},
error: function(xhr, errmsg, err) {
alert("Could not send data: " + errmsg);
}
});
});
});
</script>
</body>
</html>

Ensure CSRF tokens are handled appropriately if you're not using


@csrf_exempt.

Step 4: Update URL Patterns

Include the AJAX view in your URL patterns in urls.py:

from django.urls import path


from .views import register_student

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

urlpatterns = [
path('register_student/', register_student, name='register_student'),
]

2. This program will demonstrate how to implement a live search


feature using AJAX to display courses enrolled by a student being
searched.

Step 1: Set Up Your Django Models and Views

Assuming a relationship exists between Student and Course, ensure your


views.py can handle an AJAX search:

from django.http import JsonResponse


from .models import Student

def search_students(request):
if request.method == 'GET' and request.is_ajax():
query = request.GET.get('query')
if query:
students = Student.objects.filter(name__icontains=query).values('id',
'name')
return JsonResponse(list(students), safe=False)
return JsonResponse({"error": "No data found"}, status=400)

Step 2: Implement the AJAX Search in Template

Create the template with the search field and AJAX logic:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Course Search</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></
script>
</head>
<body>
<input type="text" id="searchQuery" placeholder="Search students...">
<ul id="results"></ul>
MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR
FULLSTACK DEVELOPMENT (21CS62)

<script>
$(document).ready(function() {
$('#searchQuery').on('keyup', function() {
$.ajax({
type: 'GET',
url: '{% url "search_students" %}',
data: {
'query': $(this).val()
},
dataType: 'json',
success: function(response) {
$('#results').empty();
response.forEach(function(student) {
$('#results').append(`<li>${student.name}</li>`);
});
},
error: function(xhr, errmsg, err) {
console.log("No data found: " + errmsg);
}
});
});
});
</script>
</body>
</html>

Step 3: Update URL Patterns

Include the search view in your URL patterns in urls.py:

from django.urls import path


from .views import search_students

urlpatterns = [
path('search_students/', search_students, name='search_students'),

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR


FULLSTACK DEVELOPMENT (21CS62)

MRIT, MYSURU SARIYA ANJUM, ASSISTANT PROFESSOR

You might also like