0% found this document useful (0 votes)
26 views

FullStack Development Manual

Uploaded by

srushtim1420
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

FullStack Development Manual

Uploaded by

srushtim1420
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 113

Fullstack Development (21CS62) 2023-24

SJM INSTITUTE OF TECHNOLOGY


P.B. No 73, NH4 By-Pass, Chitradurga - 577502

Department of Computer Science and Engineering

Full Stack Development Laboratory (21CS62)

VI- Semester

Prepared by
Prof. Pavithra
N Prof. Ambika
S

Dept. of CS&E, SJMIT, Chitradurga Page 1


Fullstack Development (21CS62) 2023-24

SJM INSTITUTE OF TECHNOLOGY

(Affiliated to Visvesvaraya Technological University, Belagavi – VTU)

P.B No.73, NH4 Bypass Road, Chitradurga – 577502.

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

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.

Program Outcome’s (PO’s)

PO 1: Apply the knowledge of Mathematics, Science and Computer Engineering to identify,


formulate and solve any engineering problems with varied complexity.

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 3: Design and conduct experiments as well as analyze and interpret data.

PO 4: Communicate and Present the information effectively.

PO 5: Use the techniques, skills and modern engineering tools necessary for engineering
practice.

Dept. of CS&E, SJMIT, Chitradurga Page 2


Fullstack Development (21CS62) 2023-24

PO 6: Handle various technical, administrative and managerial responsibilities successfully in


any organizations globally.

PO 7: Get Recognize as successful Entrepreneur globally.

PO 8: Demonstrate commitment in handling any responsibilities with professional, ethical and


social importance.

PO 9: Engage in lifelong learning to upgrade their engineering skills consistently.

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.

Program Specific Outcomes (PSO’s)

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

Dept. of CS&E, SJMIT, Chitradurga Page 3


Fullstack Development (21CS62) 2023-24

Course Learning Objectives (CLO)

CLO 1. Explain the use of learning full stack web development.

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.

Course outcomes (CO)

At the end of the course the student will be able to:

CO 1. Understand the working of MVT based full stack web development with Django.

CO 2. Designing of Models and Forms for rapid development of web pages.

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,

Dept. of CS&E, SJMIT, Chitradurga Page 4


Fullstack Development (21CS62) 2023-24

Full Stack Development Laboratory

Subject Code: 21CS62 I.A. Marks: 20


Hours/Week: 02 Total Hours: 20

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.

Dept. of CS&E, SJMIT, Chitradurga Page 5


Fullstack Development (21CS62) 2023-24

FULL STACK DEVELOPMENT

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

 HTML (Hypertext Markup Language): Used for structuring web pages.


 CSS (Cascading Style Sheets): Used for styling the appearance of web pages.
 JavaScript: A programming language used for adding interactivity and dynamic behavior
to web pages.
 Front-end frameworks/libraries such as React.js, AngularJS, or Vue.js: These provide
tools and utilities for building user interfaces and managing application state.

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.

Development Tools and Environment:

 Version control systems like Git for managing code changes.


 Integrated Development Environments (IDEs) such as Visual Studio Code, Sublime Text,
or Atom.
 Command-line tools for tasks like package management (npm for Node.js, pip for
Python, nugget for .Net), running servers, and deployment.

Why Django?

 Rapid Development: - DRY (Don‟t repeat yourself)

 Saves Time and Money

Dept. of CS&E, SJMIT, Chitradurga Page 6


Fullstack Development (21CS62) 2023-24

 Rounded Solution

 Great Exposure

 Complete Ownership

 Greater opportunity with more learning

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

 Batteries Included Philosophy (Model Forms)

 Built in database (SQLite DB)

What is Django?

 Django is a free and open source web application framework which offers fast and effective
dynamic website development.

 It is written using python.

 It follows MVT (model, view and template architecture)

Framework

A framework is a pre-built collection of libraries, modules, and tools that provides a structured
approach to developing software applications.

 Django is a web development framework.

 AngularJS is a Web Frontend development framework.

Dept. of CS&E, SJMIT, Chitradurga Page 7


Fullstack Development (21CS62) 2023-24

Django Evolution

1. Write a Web application from scratch.

2. Write another Web application from scratch.

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.

5. Repeat steps 2–4 several times. 6. Realize you‟ve invented a framework.

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.

 Less code - Ensures effective development

 Not repeated- Everything should be developed in precisely one place instead of repeating it
again

 Fast development- Django's offers fast and reliable application development.

 Consistent design - Django maintains a clean design and makes it easy to follow the best web
development practices.

Dept. of CS&E, SJMIT, Chitradurga Page 8


Fullstack Development (21CS62) 2023-24

Python Virtual Environment

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

 There are no limits to the number of virtual environments.

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

Installation of Python and Visual Studio code editors can be demonstrated.

 Python download Link: https://www.python.org/downloads/

 Visual Studio Code download and installation link: https://code.visualstudio.com/

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)

 Open cmd inside “hello_world”

 Create virtual env inside “hello_world” with the name “hello_world_venv”

python –m venv <name_ of_ virtual_env>

python –m venv hello_world_venv

Dept. of CS&E, SJMIT, Chitradurga Page 9


Fullstack Development (21CS62) 2023-24

Open project root folder in VS code

 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

 Open VS code terminal and install django framework.

pip install django

 Check whether django installation is correct

python manage.py runserver

 Create the django project with the name “hello_world_proj” inside the project root folder
“hello_world”

django-admin startproject proj

 Create the django app with the name “hello_world_app”

python manage.py startapp hello_world_app

Dept. of CS&E, SJMIT, Chitradurga Page 10


Fullstack Development (21CS62) 2023-24

SAMPLE PROGRAMS

1. Helloworld

views.py
from django.http import HttpResponse
from django. Shortcuts import render

# Create your views here.

def hello(request):

resp="<h1>Hello World!!!!</h1>”

return HttpResponse (resp)

urls.py

from django.contrib import admin


from django.urls import path
from hello_world_app.views import hello
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/',hello),
]

OUTPUT

Dept. of CS&E, SJMIT, Chitradurga Page 11


Fullstack Development (21CS62) 2023-24

2. GreetUser
views.py
from django.shortcuts import render

# Create your views here.

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

from greetUserApp.views import greet


urlpatterns =
[
path('admin/', admin.site.urls),
path('greet//',greet),
]

greet.html

<!DOCTYPE html>
<html>
<head>
<title>Greet App</title>

</head>

Dept. of CS&E, SJMIT, Chitradurga Page 12


Fullstack Development (21CS62) 2023-24

<body>
<h1>{{user}} Good afternoon! Welcome to FDP on Full stack development</h1>
</body>
</html>

OUTPUT

Dept. of CS&E, SJMIT, Chitradurga Page 13


Fullstack Development (21CS62) 2023-24

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

Visit the link https://www.python.org to download the latest release of Python.

Step - 1: Select the Python's version to download.

Click on the download button to download the exe file of Python.

Dept. of CS&E, SJMIT, Chitradurga Page 14


Fullstack Development (21CS62) 2023-24

Step - 2: Click on the Install Now

Double-click the executable file, which is downloaded.

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.

Dept. of CS&E, SJMIT, Chitradurga Page 15


Fullstack Development (21CS62) 2023-24

Step - 3 Installation in Process

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

Dept. of CS&E, SJMIT, Chitradurga Page 16


Fullstack Development (21CS62) 2023-24

Step - 4: Verifying the Python Installation

To verify whether the python is installed or not in our system, we have to do the following.

 Go to "Start" button, and search “cmd ".


 Then type, " python - - version ".
 If python is successfully installed, then we can see the version of the python installed.
 If not installed, then it will print the error as “„python‟ is not recognized as an internal or
external command, operable program or batch file. ".

We are ready to work with the Python.

Step - 5: Opening idle

Dept. of CS&E, SJMIT, Chitradurga Page 17


Fullstack Development (21CS62) 2023-24

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 – 2: Click on the below highlighted link for any OS.

Dept. of CS&E, SJMIT, Chitradurga Page 18


Fullstack Development (21CS62) 2023-24

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.

Dept. of CS&E, SJMIT, Chitradurga Page 19


Fullstack Development (21CS62) 2023-24

Step – 5: Now accept the license agreement.

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.

Dept. of CS&E, SJMIT, Chitradurga Page 20


Fullstack Development (21CS62) 2023-24

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.

Dept. of CS&E, SJMIT, Chitradurga Page 21


Fullstack Development (21CS62) 2023-24

Step – 9: The installation of VS Code will now begin.

Step – 10: At this step, we have completed installing VS Code, click on Finish.

Dept. of CS&E, SJMIT, Chitradurga Page 22


Fullstack Development (21CS62) 2023-24

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

To install Django, first visit to Django official site (https://www.djangoproject.com) and


download Django by clicking on the download section.

Dept. of CS&E, SJMIT, Chitradurga Page 23


Fullstack Development (21CS62) 2023-24

Dept. of CS&E, SJMIT, Chitradurga Page 24


Fullstack Development (21CS62) 2023-24

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

Step-01: Open Visual Studio Code

Step-02: Create a new folder for your project

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.

Dept. of CS&E, SJMIT, Chitradurga Page 25


Fullstack Development (21CS62) 2023-24

Step-03: Open the integrated terminal

In VS Code, go to View > Terminal or use the keyboard shortcut Ctrl+`` (Windows/Linux) or
Cmd+`' (macOS) to open the integrated terminal.

Step-03: Create a virtual environment

In the terminal, run the following command to create a new virtual environment:

python -m venv env

Step-04: Activate the virtual environment

Dept. of CS&E, SJMIT, Chitradurga Page 26


Fullstack Development (21CS62) 2023-24

Step-05: Install Django with the virtual environment active, install Django by running the
following command in the terminal: pip install django

Step-06: Create a new Django project

Run the following command to create a new Django project:

django-admin startproject myproject [change Project name as You Desired]

Dept. of CS&E, SJMIT, Chitradurga Page 27


Fullstack Development (21CS62) 2023-24

Step-07: Create a new Django app

In the VS Code terminal, navigate to your project directory:

cd myproject [change Project name as You Desired]

Create a new Django app by running the following command

python manage.py startapp myapp

[Replace myapp with the name you want to give to your app.]

Step-08: Add the app to the INSTALLED_APPS list

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

Dept. of CS&E, SJMIT, Chitradurga Page 28


Fullstack Development (21CS62) 2023-24

Here is the Django project structure that you wanted to create

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)

Dept. of CS&E, SJMIT, Chitradurga Page 29


Fullstack Development (21CS62) 2023-24

Step-08: Apply the migrations

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.

Here Displays the Development Server after Running Server

Dept. of CS&E, SJMIT, Chitradurga Page 30


Fullstack Development (21CS62) 2023-24

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.

Step-02: Add the app to INSTALLED_APPS

Open the settings.py file in your project's directory (e.g., myproject/settings.py).

Locate the INSTALLED_APPS list and add the name of your new app to the list:

Dept. of CS&E, SJMIT, Chitradurga Page 31


Fullstack Development (21CS62) 2023-24

Step-03: Create a view function

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

Views.py

from django.shortcuts import render


import datetime

def current_datetime(request):
now = datetime.datetime.now ()
context = {'datetime': now}

Dept. of CS&E, SJMIT, Chitradurga Page 32


Fullstack Development (21CS62) 2023-24

return render (request, 'current_datetime.html', context)

Step-04: Create a template

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

Dept. of CS&E, SJMIT, Chitradurga Page 33


Fullstack Development (21CS62) 2023-24

<script src="https://cdn.jsdelivr.net/npm/[email protected]

alpha1/dist/js/bootstrap.min.js"></script>

</body>

</html>

Step-05: Map the view function to a URL

from django. urls import path


from. import views
urlpatterns =
[
path ('', views. current_datetime, name='current_datetime'),
]

This maps the current_datetime view function to the root URL (/).

Dept. of CS&E, SJMIT, Chitradurga Page 34


Fullstack Development (21CS62) 2023-24

Step-06: Include the app's URLs in the project's URL patterns

Urls.py

from django.contrib import admin


from django.urls import include,
path
urlpatterns = [
path(„admin/‟,admin.site.urls),
path(„‟, include(„datetimeapp.urls‟)),
]

Step-07: Run the development server

python manage.py runserver

Open your web browser and visit http://127.0.0.1:8000/.

Dept. of CS&E, SJMIT, Chitradurga Page 35


Fullstack Development (21CS62) 2023-24

OUTPUT

Final Output of the Date and Time App

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.

Step-02: Add the app to INSTALLED_APPS

Open the settings.py file in your project's directory (e.g., myproject/settings.py).

Locate the INSTALLED_APPS list and add the name of your new app to the list:

Dept. of CS&E, SJMIT, Chitradurga Page 36


Fullstack Development (21CS62) 2023-24

Step-03: Create a view function

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)

Dept. of CS&E, SJMIT, Chitradurga Page 37


Fullstack Development (21CS62) 2023-24

Step-04: Create a new template


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Date and Time Offsets</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>{{ current_datetime }}</p>
<h2>Four Hours Ahead</h2>
<p>{{ four_hours_ahead }}</p>
<h2>Four Hours Before</h2>
<p>{{ four_hours_before }}</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>

Dept. of CS&E, SJMIT, Chitradurga Page 38


Fullstack Development (21CS62) 2023-24

Step-05: Map the view function to a URL


from django.urls import path
from . import views
urlpatterns = [
path('datetime-offsets/', views.datetime_offsets, name='datetime_offsets'),
]

Dept. of CS&E, SJMIT, Chitradurga Page 39


Fullstack Development (21CS62) 2023-24

Step-06: Include the app's URLs in the project's URL patterns


from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path(„admin/‟,admin.site.urls),
path(„‟, include(„datetimeapp.urls‟),
path('', include('fourdate_timeapp.urls')),
]

Step-07: Run the development server


python manage.py runserver
Open your web browser and visit http://127.0.0.1:8000/.
• Type or copy this http://127.0.0.1:8000/datetime-offsets/

Dept. of CS&E, SJMIT, Chitradurga Page 40


Fullstack Development (21CS62) 2023-24

Final Output of the Date and Time App

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.

Step-02: Add the app to INSTALLED_APPS


Open the settings.py file in your project's directory (e.g., myproject/settings.py). Locate the
INSTALLED_APPS list and add the name of your new app to the list:

Dept. of CS&E, SJMIT, Chitradurga Page 41


Fullstack Development (21CS62) 2023-24

Step-03: Create a view function


Views.py
from django.shortcuts import render
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)

Step-04: Create a new template


<!DOCTYPE html>
<html>
<head>
<title>Fruits and Students</title>
<!-- Add Bootstrap CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
rel="stylesheet">

<style>

/* Center content vertically */

html, body {

height: 100%;

Dept. of CS&E, SJMIT, Chitradurga Page 42


Fullstack Development (21CS62) 2023-24

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

Dept. of CS&E, SJMIT, Chitradurga Page 43


Fullstack Development (21CS62) 2023-24

Step-05: Map the view function to a URL


from django.urls import path
from . import views
urlpatterns = [
path('home/', views.home, name='home'),
]

Dept. of CS&E, SJMIT, Chitradurga Page 44


Fullstack Development (21CS62) 2023-24

Step-06: Include the app's URLs in the project's URL patterns


from django.contrib import admin
from django.urls import include,
path
urlpatterns = [
path(„admin/‟,admin.site.urls),
path(„‟, include(„datetimeapp.urls‟),
path('', include('fourdate_timeapp.urls'),
path('', include(listfruitapp.urls')),
]

Step-07: Run the development server


python manage.py runserver
Open your web browser and visit http://127.0.0.1:8000/.

Dept. of CS&E, SJMIT, Chitradurga Page 45


Fullstack Development (21CS62) 2023-24

Type or copy this http://127.0.0.1:8000/home/


Final Output of the Unorder list of Fruits and Students

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

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.

Dept. of CS&E, SJMIT, Chitradurga Page 46


Fullstack Development (21CS62) 2023-24

Step-02: Add the app to INSTALLED_APPS

Open the settings.py file in your project's directory (e.g., fullstack_project/settings.py).

Locate the INSTALLED_APPS list and add the name of your new app to the list:

Step-03: Create a new template


• Inside the portfolioapp/templates/ portfolio directory, create the following files:
layout.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}{% endblock %}</title>
<!-- Include Bootstrap CSS from CDN -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
/* Add some basic styling */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
header {
background-color: #333;

Dept. of CS&E, SJMIT, Chitradurga Page 47


Fullstack Development (21CS62) 2023-24

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>&copy; 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;

Dept. of CS&E, SJMIT, Chitradurga Page 49


Fullstack Development (21CS62) 2023-24

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

Dept. of CS&E, SJMIT, Chitradurga Page 50


Fullstack Development (21CS62) 2023-24

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

Dept. of CS&E, SJMIT, Chitradurga Page 51


Fullstack Development (21CS62) 2023-24

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

Dept. of CS&E, SJMIT, Chitradurga Page 52


Fullstack Development (21CS62) 2023-24

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
{% endblock %}

Step-04: Create a view function

portfolioapp/views.py

from django.shortcuts import render


def main(request):
return render(request, 'portfolio/home.html')
def about(request):
return render(request, 'portfolio/about.html')
def contact(request):
return render(request, 'portfolio/contact.html')

Dept. of CS&E, SJMIT, Chitradurga Page 53


Fullstack Development (21CS62) 2023-24

Step-05: Map the view function to a URL


Urls.py

from django.urls import path


from . import views
urlpatterns = [
path('main/', views.main, name='main'),
path('about/', views.about, name='about'),
path('contact/', views.contact, name='contact'),
]

Step-06: Include the app's URLs in the project's URL patterns

fullstack_project/urls.py

from django.contrib import admin


from django.urls import include,
path
urlpatterns = [
path(„admin/‟,admin.site.urls),
path(„‟, include(„datetimeapp.urls‟),
path('', include('fourdate_timeapp.urls'),
path('', include(portfolioapp.urls')),
]

Dept. of CS&E, SJMIT, Chitradurga Page 54


Fullstack Development (21CS62) 2023-24

Step-07: Run the development server

python manage.py runserver

• Open your web browser and visit http://127.0.0.1:8000/.

• Type or copy this http://127.0.0.1:8000/main/

Final Output by Clicking Above Navbar Home, About Us, Contact Us Buttons

Figure: Home Page Screen

Figure: About Us Screen

Dept. of CS&E, SJMIT, Chitradurga Page 55


Fullstack Development (21CS62) 2023-24

Figure: About Us Screen

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.

Step-02: Add the app to INSTALLED_APPS


Open the settings.py file in your project's directory (e.g., fullstack_project/settings.py).
Locate the INSTALLED_APPS list and add the name of your new app to the list:

Dept. of CS&E, SJMIT, Chitradurga Page 56


Fullstack Development (21CS62) 2023-24

Step-03: Create models

from django.db import models


class Course(models.Model):
name = models.CharField(max_length=255)
description = models.TextField(blank=True, null=True)
def str (self):
return self.name
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='')
def str (self):
courses = models.ManyToManyField(Course, related_name='students', blank=True)
return f"{self.first_name} {self.last_name}"

Step-04: Register models in the admin site

from django.contrib import admin

from .models import Course, Student

admin.site.register(Course)

admin.site.register(Student)

Dept. of CS&E, SJMIT, Chitradurga Page 57


Fullstack Development (21CS62) 2023-24

Step-05: Create forms

forms.py

from django import forms


from .models import Student, Course
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['first_name', 'last_name', 'email', 'courses']
widgets = {
'first_name': forms.TextInput(attrs={'class': 'form-control'}),
'last_name': forms.TextInput(attrs={'class': 'form-control'}),
'email': forms.EmailInput(attrs={'class': 'form-control'}),
'courses':
'dropdown'}),
}
forms.SelectMultiple(attrs={'class':

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

Dept. of CS&E, SJMIT, Chitradurga Page 58


Fullstack Development (21CS62) 2023-24

Step-06: Create views

Views.py

from django.shortcuts import render, redirect


from .models import Course, Student
from .forms import StudentForm, CourseForm
def index(request):
courses = Course.objects.all()
def register_student(request):
return render(request, 'registration/index.html', {'courses': courses})
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()
return redirect('index')
else
form = StudentForm()
return render(request, 'registration/register_student.html', {'form': form})
def register_course(request):

Dept. of CS&E, SJMIT, Chitradurga Page 59


Fullstack Development (21CS62) 2023-24

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

Step-07: Create templates


index.html
{% extends 'base.html' %}
{% block content %}
<div class="container">
<h1 class="mt-5">Courses</h1>

Dept. of CS&E, SJMIT, Chitradurga Page 60


Fullstack Development (21CS62) 2023-24

<ul class="list-group mt-3">


{% for course in courses %}
<li class="list-group-item"><a href="{% url 'student_list' course.id %}">{{ course.name
}}</a></li>
{% endfor %}
</ul>
<a class="btn btn-primary mt-3" href="{% url 'register_student' %}">Register Student</a>
<a class="btn btn-secondary mt-3" href="{% url 'register_course' %}">Register Course</a>
</div>
{% endblock %}

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

Dept. of CS&E, SJMIT, Chitradurga Page 61


Fullstack Development (21CS62) 2023-24

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

Dept. of CS&E, SJMIT, Chitradurga Page 62


Fullstack Development (21CS62) 2023-24

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

Dept. of CS&E, SJMIT, Chitradurga Page 63


Fullstack Development (21CS62) 2023-24

<div class="alert alert-danger">{{ error }}</div>


{% endfor %}
</div>
{% endfor %}
</form>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary text-center">Register</button>
{% endblock %}

student_list.html
{% extends 'base.html' %}
{% block content %}
<h1>Students Registered for {{course.name}}</h1>
<ul>
{% for student in students %}
{% endfor %}
</ul>

Dept. of CS&E, SJMIT, Chitradurga Page 64


Fullstack Development (21CS62) 2023-24

{% endblock %}
<li>{{ student.first_name }} {{ student.last_name }}</li>

Step-08: Create a base template


base.html
<!DOCTYPE html>
<html>
<head>
<title>Student Registration</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>

Dept. of CS&E, SJMIT, Chitradurga Page 65


Fullstack Development (21CS62) 2023-24

Step-09: Configure URLs


from django.urls import path
from . import views
urlpatterns = [
path('index/', views.index, name='index'),

path('register-student/', views.register_student, name='register_student'),


path('register-course/', views.register_course, name='register_course'),
path('student-list/<int:course_id>/', views.student_list, name='student_list'),
]

Dept. of CS&E, SJMIT, Chitradurga Page 66


Fullstack Development (21CS62) 2023-24

Step-09: Update project URLs

Step-10: Make Migration for check Models saved or not into the database

Step-10: Migrate To Save the Models into database

Step-07: Run the development server


python manage.py runserver
Open your web browser and visit http://127.0.0.1:8000/.

Dept. of CS&E, SJMIT, Chitradurga Page 67


Fullstack Development (21CS62) 2023-24

Type or copy this http://127.0.0.1:8000/index/


Final Output By Clicking Register Student and Register Course

OUTPUT

Fig: Index Screen

Fig: Student Register Screen

Fig: Course Register Screen

Dept. of CS&E, SJMIT, Chitradurga Page 68


Fullstack Development (21CS62) 2023-24

Fig: Students Register Particular Courses Screen

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',)

Dept. of CS&E, SJMIT, Chitradurga Page 69


Fullstack Development (21CS62) 2023-24

Step-02: Create and apply migrations


python manage.py makemigrations

python manage.py migrate

Step-03: Create a superuser


python manage.py
createsuperuser

Type Username: admin


Password:1234 [For Simply but your wish to create your own username and password]

Step-03: Access the admin interface


python manage.py runserver
• Open your web browser and visit http://127.0.0.1:8000/.

• Type or copy this http://127.0.0.1:8000/admin/.

Dept. of CS&E, SJMIT, Chitradurga Page 70


Fullstack Development (21CS62) 2023-24

Step-04: Log in to the admin interface

Step-05: Add data through admin forms


Final Output

Fig: Admin Main Screen

Fig: Admin Course Screen

Dept. of CS&E, SJMIT, Chitradurga Page 71


Fullstack Development (21CS62) 2023-24

Fig: Admin Student Screen

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

Dept. of CS&E, SJMIT, Chitradurga Page 72


Fullstack Development (21CS62) 2023-24

Step 3: Create and apply migrations to create the necessary database tables.
python manage.py makemigrations

python manage.py migrate

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

Dept. of CS&E, SJMIT, Chitradurga Page 73


Fullstack Development (21CS62) 2023-24

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

Dept. of CS&E, SJMIT, Chitradurga Page 74


Fullstack Development (21CS62) 2023-24

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

Dept. of CS&E, SJMIT, Chitradurga Page 75


Fullstack Development (21CS62) 2023-24

Step 7: Create an HTML template file register_project.html in the templates/registration/


directory and render the form.
<!-- create_project.html -->
{% extends 'base.html' %}
{% block content %}
<div class="container my-3">
<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>
<label for="id_languages_used">Languages Used:</label>
<div class="form-group">
<label for="id_duration">Duration:</label>
{{ form.duration }}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
{% endblock %}

Dept. of CS&E, SJMIT, Chitradurga Page 76


Fullstack Development (21CS62) 2023-24

Step 8: add the index.html to show the registered projects


<h1 class="mt-5 my-5">Projects</h1>
<ul class="list-group mt-3">
{% for project in projects %}
<li class="list-group-item">
<a href="{% url 'project_student_list' project.id %}">{{ project.topic }}</a>
</li>
{% endfor %}
</ul>
<div class="form-group">
{{ form.project.label_tag }}
{{ form.project }}
{{ form.project.errors }}
</div>

Dept. of CS&E, SJMIT, Chitradurga Page 77


Fullstack Development (21CS62) 2023-24

Dept. of CS&E, SJMIT, Chitradurga Page 78


Fullstack Development (21CS62) 2023-24

Step 9: Add a URL pattern for the register_project in your urls.py file
path('projects_register/', views.register_project, name='register_project'),

Step-10: Run the development server


python manage.py runserver
• Open your web browser and visit http://127.0.0.1:8000/.

• Type or copy this http://127.0.0.1:8000/index/

Dept. of CS&E, SJMIT, Chitradurga Page 79


Fullstack Development (21CS62) 2023-24

Final Output by Clicking Register Project and Register Student


OUTPUT

Fig: Home Page Screen

Fig: Project Creation Screen

Fig: Project Successfully Creation Screen

Dept. of CS&E, SJMIT, Chitradurga Page 80


Fullstack Development (21CS62) 2023-24

Fig: Student Register the Project

Fig: Student Registered Particular Projects

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='')

Dept. of CS&E, SJMIT, Chitradurga Page 81


Fullstack Development (21CS62) 2023-24

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

Dept. of CS&E, SJMIT, Chitradurga Page 82


Fullstack Development (21CS62) 2023-24

Step-3: Now, let's create the templates:


stu_list.html
{% extends 'base.html' %}
{% block content %}
<h1>Students</h1>
<ul>
{% for student in students %}
<li>
<a href="{% url 'student_detail' student.pk %}">{{ student.first_name }}
{{ student.last_name }}</a>
</li>
{% endfor %}
</ul>
{% endblock %}

Dept. of CS&E, SJMIT, Chitradurga Page 83


Fullstack Development (21CS62) 2023-24

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

Dept. of CS&E, SJMIT, Chitradurga Page 84


Fullstack Development (21CS62) 2023-24

Step-4: add the URL patterns:


from django.urls import path
from .import views
path('students/', views.StudentListView.as_view(), name='student_list_all'),
path('students/<int:pk>/', views.StudentDetailView.as_view(), name='student_detail'),

Dept. of CS&E, SJMIT, Chitradurga Page 85


Fullstack Development (21CS62) 2023-24

Step-5: add Index.html For showing the Students In Main Page:


Index.html
<h1 class="mt-5 my-5">Students</h1>
<ul class="list-group mt-3">
{% for student in students %}
<li class="list-group-item">
<a href="{% url 'student_detail' student.pk %}">{{ student.first_name }}
{{ student.last_name }}</a>
</li>
{% endfor %}
</ul>

Step-6: Run the development server


python manage.py runserver
• Open your web browser and visit http://127.0.0.1:8000/.

Dept. of CS&E, SJMIT, Chitradurga Page 86


Fullstack Development (21CS62) 2023-24

• Type or copy this http://127.0.0.1:8000/index/

Final Output By Clicking Register Project and Register Student

OUTPUT

Fig: Main Screen

Fig: List View of Students Screen

Dept. of CS&E, SJMIT, Chitradurga Page 87


Fullstack Development (21CS62) 2023-24

Fig: Detailed View of Student Screen

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.

Step-02: Add the app to INSTALLED_APPS


Open the settings.py file in your project's directory (e.g., fullstack_project/settings.py).
Locate the INSTALLED_APPS list and add the name of your new app to the list:

Dept. of CS&E, SJMIT, Chitradurga Page 88


Fullstack Development (21CS62) 2023-24

Step-03: Create models


models.py
from django.db import 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
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
from .models import Book

Dept. of CS&E, SJMIT, Chitradurga Page 89


Fullstack Development (21CS62) 2023-24

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

Dept. of CS&E, SJMIT, Chitradurga Page 90


Fullstack Development (21CS62) 2023-24

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 {

Dept. of CS&E, SJMIT, Chitradurga Page 91


Fullstack Development (21CS62) 2023-24

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>

Dept. of CS&E, SJMIT, Chitradurga Page 92


Fullstack Development (21CS62) 2023-24

</html>

Step-05: add the URL patterns and import Necessary Packages.

from django.urls import path


from books.views import export_books_csv, export_books_pdf
urlpatterns = [
path('books/export/csv/', export_books_csv, name='export_books_csv'),
path('books/export/pdf/', export_books_pdf, name='export_books_pdf'),
]

Dept. of CS&E, SJMIT, Chitradurga Page 93


Fullstack Development (21CS62) 2023-24

Step-06: Install the xhtml2pdf library for generating PDF files.


pip install xhtml2pdf

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

from django.db import migrations

def create_book_data(apps, schema_editor):

Book = apps.get_model('books', 'Book')

Book.objects.bulk_create([

Book(title='To Kill a Mockingbird', author='Harper Lee', publication_date='1960-07-11'),

Book(title='1984', author='George Orwell', publication_date='1949-06-08'),

Book(title='Pride and Prejudice', author='Jane Austen', publication_date='1813-01-28'),

Dept. of CS&E, SJMIT, Chitradurga Page 94


Fullstack Development (21CS62) 2023-24

Book(title='The Great Gatsby', author='F. Scott Fitzgerald', publication_date='1925-04-10'),


Book(title='The Catcher in the Rye', author='J.D. Salinger', publication_date='1951-07-16'),
])
class Migration(migrations.Migration):
dependencies =
[ ('books',
'0001_initial'),
]
operations = [
]
migrations.RunPython(create_book_data),

Run the following command to apply the data migration


python manage.py migrate
Step-08: Custom Script
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fullstack_project.settings')
import django
django.setup()
from books.models import Book
Book.objects.bulk_create([
Book(title='To Kill a Mockingbird', author='Harper Lee', publication_date='1960-07-11'),
Book(title='1984', author='George Orwell', publication_date='1949-06-08'),
Book(title='Pride and Prejudice', author='Jane Austen', publication_date='1813-01-28'),
Book(title='The Great Gatsby', author='F. Scott Fitzgerald', publication_date='1925-04-10'),
Book(title='The Catcher in the Rye', author='J.D. Salinger', publication_date='1951-07-16‟),
])

Dept. of CS&E, SJMIT, Chitradurga Page 95


Fullstack Development (21CS62) 2023-24

Run the script using the following command:

python create_book_data.py

Step-09: Update project URLs


Urls.py

Dept. of CS&E, SJMIT, Chitradurga Page 96


Fullstack Development (21CS62) 2023-24

Step-09: Run the development server


python manage.py runserver
• Open your web browser and visit http://127.0.0.1:8000/.

• Type or copy this http://127.0.0.1:8000/books/export/csv/

Final Output by Clicking Register Project and Register Student


OUTPUT

Fig: CSV File Download Screen

Dept. of CS&E, SJMIT, Chitradurga Page 97


Fullstack Development (21CS62) 2023-24

• Type or copy this http://127.0.0.1:8000/books/export/pdf/

Fig: PDF File Download Screen

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.

Step-02: Add the app to INSTALLED_APPS


Open the settings.py file in your project's directory (e.g., fullstack_project/settings.py).
Locate the INSTALLED_APPS list and add the name of your new app to the list.

Dept. of CS&E, SJMIT, Chitradurga Page 98


Fullstack Development (21CS62) 2023-24

Step-03: Create models

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='')

Dept. of CS&E, SJMIT, Chitradurga Page 99


Fullstack Development (21CS62) 2023-24

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

Dept. of CS&E, SJMIT, Chitradurga Page 100


Fullstack Development (21CS62) 2023-24

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

Step-06: In your app, create a templates directory and an html file


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

Dept. of CS&E, SJMIT, Chitradurga Page 101


Fullstack Development (21CS62) 2023-24

<script src="{% static 'js/jquery.min.js' %}"></script>


</head>
<body>
<div class="container">
<h1>Student Registration</h1>
<form id="student-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 %}
<div class="alert alert-danger">{{ error }}</div>
{% endfor %}
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<div id="response"></div>
</div>
<script>
$(document).ready(function() {
$('#student-form').on('submit', function(e) {
e.preventDefault();

Dept. of CS&E, SJMIT, Chitradurga Page 102


Fullstack Development (21CS62) 2023-24

var formData = $(this).serialize();


$.ajax({
type: 'POST',
url: '{% url "student" %}',
data: formData,
success: function(response) {
if (response.success) {
$('#response').html('<div class="alert alert-success">Student registered successfully.</div>');
$('#student-form')[0].reset();
} else {
$('#response').html ('<div class="alert alert-danger">an error occurred. Please try again.</div>');
}
});
});
});
</script>
</body>
</html>

Dept. of CS&E, SJMIT, Chitradurga Page 103


Fullstack Development (21CS62) 2023-24

Step-07: Update app URLs


# project/urls.py
from django.urls import path
from books.views import export_books_csv, export_books_pdf
urlpatterns = [
path('books/export/csv/', export_books_csv, name='export_books_csv'),
path('books/export/pdf/', export_books_pdf, name='export_books_pdf'),
]

Step-08: Update project URLs


Urls.py

Step-09: Run the development server


python manage.py runserver
• Open your web browser and visit http://127.0.0.1:8000/.

Dept. of CS&E, SJMIT, Chitradurga Page 104


Fullstack Development (21CS62) 2023-24

• Type or copy this http://127.0.0.1:8000/student/

Fig: Student Registration Screen

Fig: Student Registration Success Message Screen

Dept. of CS&E, SJMIT, Chitradurga Page 105


Fullstack Development (21CS62) 2023-24

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

Step-02: Create View Function in a student_course_registration_app views.py


def search_students(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax:
query = request.GET.get('query', '')
students = Student.objects.filter(first_name icontains=query) |
Student.objects.filter(last_name icontains=query)
results = [ ]
for student in students:
student_data = {
'id': student.id,
'name': f"{student.first_name} {student.last_name}",
'email': student.email,
'courses': [course.name for course in student.courses.all()]
}
results.append(student_data)
return JsonResponse({'results': results})
return render(request, 'registration/search.html')

Dept. of CS&E, SJMIT, Chitradurga Page 106


Fullstack Development (21CS62) 2023-24

Step-02: Create Templates in a student_course_registration_app


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({ hea
ders: {
'X-CSRFToken': '{{ csrf_token }}'
}
});
$(document).ready(function() {
$('#search-input').on('input', function() {

Dept. of CS&E, SJMIT, Chitradurga Page 107


Fullstack Development (21CS62) 2023-24

var query = $(this).val();


$.ajax({
url: '{% url "search_students" %}',
data: {
'query': query
},
success: function(data) {
var results =
data.results; var html =
'';
if (results.length > 0) {
html += '<ul class="list-group">';
for (var i = 0; i < results.length; i++)
{ var student = results[i];
html += '<li class="list-group-item">';
html += '<h5>' + student.name + '</h5>';
html += '<p><strong>Email:</strong> ' + student.email + '</p>';
html += '<p><strong>Courses:</strong> ' + student.courses.join(', ') + '</p>';
html += '</li>';
}
html += '</ul>';
} else {
html += '<p>No students found.</p>';
}
$('#search-results').html(html);
}
});

Dept. of CS&E, SJMIT, Chitradurga Page 108


Fullstack Development (21CS62) 2023-24

});

Dept. of CS&E, SJMIT, Chitradurga Page 109


Fullstack Development (21CS62) 2023-24

});
</script>
</head>
<body>
{% csrf_token %}
<div class="container">
<h1>Search Students</h1>
</div>
</body>

<input type="text" id="search-input" class="form-control" placeholder="Search for a


student...">
<div id="search-results"></div>
</html>

Dept. of CS&E, SJMIT, Chitradurga Page 110


Fullstack Development (21CS62) 2023-24

Step-03: Update app URLs


urls.py

Step-04: Make migrations and migrate if any changes are made in your application eg.
Models etc..

Step-05: Run the development server


python manage.py runserver
• Open your web browser and visit http://127.0.0.1:8000/.

Dept. of CS&E, SJMIT, Chitradurga Page 111


Fullstack Development (21CS62) 2023-24

• Type or copy this http://127.0.0.1:8000/search/

Fig: Before Search Result contains only Search Bar Screen

Fig: Search Screen

Dept. of CS&E, SJMIT, Chitradurga Page 112


Fullstack Development (21CS62) 2023-24

Dept. of CS&E, SJMIT, Chitradurga Page 113

You might also like