FSD Lab Manual
FSD Lab Manual
https://www.python.org/downloads/
https://code.visualstudio.com/
Django installation:
Open a command prompt and type following command:
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
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.
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
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
After:
After:
Click on http://127.0.0.1:8000/
Updated Code:
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")
Demonstrations 2:
Now, go to the urls.py in the project “Module1” and modify line no. 18 and 24 and observe
the terminal:
ow,
go to the views.py in the app “program1” and add the below contents:
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
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
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= [
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
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.
After:
After:
Add ‘program2’ under INSTALLED_APPS:
Now, go to urls.py under the project “Module1” and add the path:
Now, go to views.py under the app “program2” and add the code:
Updated Code:
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)
Now, create urls.py in the app “Program2” and add the below path:
***
Program 1: Develop a simple Django app that displays an unordered list of fruits and
ordered list of selected students for an event.
urlpatterns = [
path('admin/', admin.site.urls),
path('program3/',include("program3.urls"))
]
from django.shortcuts import render #Render will render the templet, here
it is html
from . models import Student #importing from the Student models.py
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)
<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>
urlpatterns=[
path('lists/',display_list),
]
Now, migrate
PS C:\Users\User\OneDrive\Desktop\FSD\FDP> python manage.py makemigrations
Now,
Now,
PS C:\Users\User\OneDrive\Desktop\FSD\FDP> python manage.py runserver
Now,
http://127.0.0.1:8000/program3/lists/
Now,
PS C:\Users\User\OneDrive\Desktop\FSD\FDP> python manage.py createsuperuser
And give username, email ID and password
127.0.0.1:8000/admin:
127.0.0.1:8000/progarm3/lists/:
Now, it is complete
We don’t need models for fruits as they can be hardcoded, but let’s create
a model for students.
In `myapp/models.py`:
name = models.CharField(max_length=100)
def __str__(self):
return self.name
In `myapp/views.py`:
def display_lists(request):
fruits = ['Apple', 'Banana', 'Cherry', 'Date']
students = Student.objects.all()
return render(request, 'myapp/display_lists.html', {'fruits': fruits,
'students': students})
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`:
urlpatterns = [
path('lists/', display_lists),
]
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>
{% block content %}
<h1>Welcome to Our Site!</h1>
<p>This is the home page.</p>
{% endblock %}
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
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})
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>
</div>
<button type="submit" class="btn
btn-primary">Register</button>
</form>
</div>
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>
1.Set up and customize the Django admin panel for Student and
Course models. Perform migrations and use the admin to manage data
entry.
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:
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
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)
admin.site.register(Student)
admin.site.register(Course)
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')
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.
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):
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
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['name', 'project']
widgets = {
'project': forms.HiddenInput(), # Initially hidden, set via another form or
view logic
}
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})
First, you will need to define the URL patterns that will route to the generic
views.
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'
<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.
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
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
class Student(models.Model):
name = models.CharField(max_length=100)
# Add additional fields if necessary
def __str__(self):
return self.name
@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)
<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>
urlpatterns = [
path('register_student/', register_student, name='register_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)
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>
urlpatterns = [
path('search_students/', search_students, name='search_students'),