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

Django Framework23072024

Uploaded by

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

Django Framework23072024

Uploaded by

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

21CS62 Course Title : Fullstack Development

Django Framework

Django
DEVELOPMENT KIT

MALLIKARJUNA GD Page1 | 280


21CS62 Course Title : Fullstack Development

Django

DEVELOPMENT KIT

MALLIKARJUNA GD Page2 | 280


21CS62 Course Title : Fullstack Development

PREFACE

Welcome to the world of Django Fullstack development

In this book, we embark on a journey to explore one of the most powerful and versatile web
development frameworks available today. Django, renowned for its simplicity, scalability, and
robustness, empowers developers to create stunning, feature-rich web applications with ease.

Key Features of this Ebook:

Comprehensive Framework: Django provides a comprehensive toolkit that covers all aspects of web
development, including URL routing, template engine, object-relational mapping (ORM),
authentication, and more. With Django, you have everything you need to build a full-fledged web
application right out of the box.

Batteries Included: Django follows the principle of "batteries included," meaning it comes with a wide
range of built-in features and utilities to streamline development. From an admin interface for
managing site content to a powerful ORM for interacting with the database, Django takes care of
common web development tasks so you can focus on building unique and innovative features.

Scalability and Performance: Whether you're building a small blog or a high-traffic social media
platform, Django scales effortlessly to meet your needs. Its architecture is designed for performance,
with features like caching, database optimization, and support for asynchronous tasks ensuring your
application can handle increased load without sacrificing speed or reliability.

Who This Book Is For:

This book is intended for developers of all skill levels who want to master Django Fullstack
development. Whether you're a seasoned web developer looking to add Django to your toolkit or a
newcomer to web development eager to learn from scratch, this book will guide you through the
process of building dynamic and engaging web applications with Django.

What You'll Learn:

• Setting up a Django development environment


• Creating and managing Django projects and applications
• Working with models, views, templates, and URLs
• Integrating authentication and authorization into your application
• Handling forms, file uploads, and user input validation
• Implementing RESTful APIs for mobile and web clients
• Optimizing performance and scalability for production deployment
• And much more!

Thank you for joining us on this journey into the exciting world of Django Fullstack development. Let's
get started!

Happy coding!

Warm Regards,

Mallikarjuna G D
Ph: +91 9739201041
Mail: [email protected]

MALLIKARJUNA GD Page3 | 280


21CS62 Course Title : Fullstack Development

TABLE OF CONTENT
MODULE-1: MVC BASED WEB DESIGNING ................................................................................ 8
1.1 INTRODUCTION ......................................................................................................... 8
1.2 INSTALLATION ........................................................................................................ 11
1.3 WEB FRAMEWORK ................................................................................................. 14
1.4 MVC DESIGN PATTERN ......................................................................................... 15
1.5 DJANGO EVOLUTION ............................................................................................. 17
1.6 PROJECT STRUCTURE ............................................................................................ 20
1.7 DJANGO ARCHITECTURE ...................................................................................... 28
1.8 DJANGO ..................................................................................................................... 31
1.9 VIEWS ........................................................................................................................ 39
1.9.1 Function-based Views (FBVs) ................................................................................. 39
1.9.2 Class-based Views (CBVs) ....................................................................................... 40
1.9.3 Generic class based view ........................................................................................ 42
1.9.4 Rendering Templates:............................................................................................. 44
1.9.5 Handling Form Submissions ................................................................................... 47
1.10 MAPPING URL TO VIEWS ...................................................................................... 48
1.11 WORKING OF DJANGO URL CONFS AND LOOSE COUPLING ....................... 49
1.11.1 URLconfs in Django: .............................................................................................. 49
1.11.2. Loose Coupling in Django URLconfs: ................................................................... 50
1.12 ERRORS IN DJANGO, WILD CARD PATTERNS IN URLS ................................. 51
1.13 IMPORTANT IMPORTS ........................................................................................... 55
1.14 PRACTICE PROGRAMS ........................................................................................... 69
1.14.1 Installation of Python, Django, and Visual Studio code editors can be
demonstrated. ...................................................................................................................... 69
1.14.2 Creation of virtual environment, Django project, and App should be
demonstrated ....................................................................................................................... 70
1.14.3 Develop a Django app that displays the current date and time in the server ....... 72
1.14.4 Develop a Django app that displays the date and time four hours ahead and four
hours before to offset the current date and time in the server. ............................................ 73
1.15 IMPORTANT NOTE .................................................................................................. 76
1.16 MCQ ............................................................................................................................ 76

MALLIKARJUNA GD Page4 | 280


21CS62 Course Title : Fullstack Development

MODULE-2: DJANGO TEMPLATES AND MODELS.................................................... 81


2.1 TEMPLATE SYSTEM BASICS ................................................................................ 82
2.2 USING THE DJANGO TEMPLATE SYSTEM......................................................... 94
2.3 BASIC TEMPLATE TAGS AND FILTERS .............................................................. 96
2.3.1 Template Tags: ....................................................................................................... 96
2.3.2 Template Filters ...................................................................................................... 97
2.4 MVT DEVELOPMENT PATTERN ........................................................................... 98
2.5 TEMPLATE LOADING ........................................................................................... 102
2.6 TEMPLATE INHERITANCE .................................................................................. 104
2.6.1. Base Template ..................................................................................................... 104
2.6.2 Child Template...................................................................................................... 105
2.6.3 Render the Child Template: .................................................................................. 106
2.7 Databases ................................................................................................................... 106
2.7.1 Configuring Databases ................................................................................... 107
2.7.2 Defining and Implementing Models .............................................................. 108
2.7.3 Basic Data Access........................................................................................... 116
2.7.3.1 Adding Model String Representations........................................................... 121
2.7.3.2 Schema Evolution .............................................................................................. 125
2.8 PRACTICE ................................................................................................................ 129
2.8.1 Develop A Simple Django App That Displays An Unordered List Of Fruits And
An Ordered List Of Selected Students For An Event ..................................................... 129
2.8.2 Develop A Layout.Html With A Suitable Header (Containing A Navigation
Menu) And Footer With Copyright And Developer Information. Inherit This Layout.Html
And Create 3 Additional Pages: Contact Us, About Us, And The Home Page Of Any
Website. 132
2.8.3 Develop A Django App That Performs Student Registration To A Course. It
Should Also Display A List Of Students Registered For Any Selected Course. Create
Students And Courses As Models With Enrolment As Manytomany Field. .................. 135
2.9 IMPORTANT NOTE ................................................................................................ 138
2.9. MCQ ........................................................................................................................... 138
MODULE-3: DJANGO ADMIN INTERFACES AND MODEL FORMS...................... 142
3.0 ACTIVATING ADMIN INTERFACES ................................................................... 143
3.1 USING ADMIN INTERFACES ............................................................................... 144

MALLIKARJUNA GD Page5 | 280


21CS62 Course Title : Fullstack Development

3.2 AUTHENTICATION AND AUTHORIZATION .................................................... 145


3.3 CUSTOMIZING ADMIN INTERFACES ................................................................ 149
3.4 FORM PROCESSING .............................................................................................. 154
3.4.1 CREATING FEEDBACK FORMS .................................................................. 168
3.4.2 FORM SUBMISSIONS .................................................................................... 170
3.4.3 CUSTOM VALIDATION ................................................................................. 172
3.4.4 CREATING MODEL FORMS ......................................................................... 175
3.4.5 URLCONF TICKS ............................................................................................ 177
3.4.6 INCLUDING OTHER URLCONFS ................................................................. 178
3.3. PRACTICE ................................................................................................................. 179
3.3.1 For student and course models created in the Lab experiment for Module 2, register
admin interfaces, perform migrations, and illustrate data entry through admin forms...... 180
3.3.2 Develop a Model form for a student that contains his topic chosen for the project,
languages used, and duration with a model called project. ............................................... 185
3.5 IMPORTANT NOTE ................................................................................................ 188
3.6 MCQ .......................................................................................................................... 188
MODULE-4: GENERIC VIEWS AND DJANGO STATE PERSISTENCE ................... 192
4.0 USING GENERIC VIEWS ....................................................................................... 192
4.1 GENERIC VIEWS OF OBJECTS .............................................................................. 205
4.2 EXTENDING GENERIC VIEWS OF OBJECTS ...................................................... 207
4.3 EXTENDING GENERIC VIEWS .............................................................................. 209
4.4 MIME TYPES ............................................................................................................. 210
4.5 GENERATING NON-HTML CONTENTS LIKE CSV AND PDF .......................... 213
4.6 SYNDICATION FEED FRAMEWORK .................................................................... 215
4.7 SITEMAP FRAMEWORK ......................................................................................... 217
4.8 COOKIES, SESSIONS ............................................................................................... 219
4.9 USERS AND AUTHENTICATION ........................................................................... 223
4.10 PRACTICES.............................................................................................................. 226
4.10.1 For student enrolment developed in Module 2, create a generic class view that
displays a list of students and a detail view that displays student details for any selected
student in the list................................................................................................................ 226
4.10.2 Develop an example Django app that performs CSV and PDF generation for any
models created in the previous laboratory component ...................................................... 228
4.10 IMPORTANT NOTE ................................................................................................ 230

MALLIKARJUNA GD Page6 | 280


21CS62 Course Title : Fullstack Development

4.11 MCQ .......................................................................................................................... 232


MODULE-5: JQUERY AND AJAX INTEGRATION IN DJANGO .............................. 235
5.0 AJAX SOLUTION .................................................................................................... 235
5.1 JAVASCRIPT ........................................................................................................... 239
5.2 XML .......................................................................................................................... 247
5.3 HTTPREQUEST AND RESPONSE......................................................................... 249
5.4 HTML ........................................................................................................................ 252
5.5 CSS ............................................................................................................................ 255
5.6 JSON ......................................................................................................................... 262
5.7 USING JQUERY UI AUTOCOMPLETE IN DJANGO .......................................... 264
5.8 PRACTICES.............................................................................................................. 267
5.12.1 Develop a registration page for student enrolment as done in Module 2 but without
page refresh using AJAX................................................................................................... 267
5.12.2 Develop a search application in Django using AJAX that displays courses enrolled
by a student being searched ............................................................................................... 271
5.9 IMPORTANT NOTE ................................................................................................ 276
5.10 MCQ .......................................................................................................................... 276

MALLIKARJUNA GD Page7 | 280


21CS62 Course Title : Fullstack Development

MODULE-1: MVC BASED WEB DESIGNING


1.1 INTRODUCTION
What is Software?

Software refers to a collection of instructions, data, and programs that enable computers to
perform specific tasks or functions. It's intangible and exists in the form of code written in
programming languages that computers can understand and execute. Software is the
interface between users and computer hardware, facilitating communication and enabling
users to interact with computers to accomplish various objectives.

What is Software Architecture Design?

Software architecture design is the process of defining the structure, components,


relationships, and behavior of a software system to meet specific requirements. It involves
making high-level design decisions that determine how the system will be organized and
how its components will interact with each other to achieve the desired functionality.

Components of software architecture design:

Component Identification: Identifying the major components or modules of the system


based on functional requirements and domain knowledge. Components represent distinct
units of functionality or logical groupings of related functionality.

Architectural Styles: Choosing an architectural style or pattern that best suits the
requirements and constraints of the system. Common architectural styles include layered
architecture, client-server architecture, microservices architecture, and event-driven
architecture.

Decomposition and Abstraction: Breaking down the system into smaller, more manageable
components through decomposition. This involves identifying subsystems, defining their
boundaries, and establishing interfaces for communication between them. Abstraction is
used to hide unnecessary details and focus on essential aspects of each component.

Communication Protocols: Defining communication protocols and data formats for


interactions between system components. This includes specifying message formats, APIs,
and protocols for communication over networks or between different layers of the system.

Data Management: Designing the data architecture of the system, including data storage,
retrieval, and manipulation. This involves selecting appropriate data storage technologies
(e.g., relational databases, NoSQL databases, file systems) and designing data models,
schemas, and access patterns.

Scalability and Performance: Considering scalability and performance requirements during


the design phase and incorporating design principles and patterns that support scalability

MALLIKARJUNA GD Page8 | 280


21CS62 Course Title : Fullstack Development

and optimize system performance. This may include techniques such as load balancing,
caching, and asynchronous processing.

Security and Reliability: Incorporating security measures and reliability mechanisms to


protect the system from security threats and ensure its resilience to failures. This includes
implementing access controls, encryption, authentication, and error handling mechanisms.

Cross-Cutting Concerns: Addressing cross-cutting concerns such as logging, monitoring, and


configuration management that affect multiple components or aspects of the system. These
concerns are typically addressed through reusable components or aspects of the
architecture that are applied across the system.

Documentation and Governance: Documenting the architecture design decisions, rationale,


and guidelines to ensure clarity and facilitate communication among stakeholders.
Establishing governance processes to manage architectural changes and ensure adherence
to architectural principles and standards.

Software architecture design is an iterative process that involves collaboration among


architects, developers, stakeholders, and other relevant parties. It requires balancing
conflicting goals and constraints, such as functionality, performance, scalability, and
maintainability, to arrive at an architecture that meets the system's and its stakeholders'
needs.

Explain Django full-stack development architecture.

Django full-stack development refers to using the Django web framework to develop both
the front-end (client-side) and back-end (server-side) components of a web application.
Django is a high-level Python web framework that enables the rapid development of secure,
scalable, and maintainable web applications.

MALLIKARJUNA GD Page9 | 280


21CS62 Course Title : Fullstack Development

Back-end Development:

• Model Layer: Define data models using Django's Object-Relational Mapping (ORM)
system. Models represent the structure of the application's data and interact with
the database.
• View Layer: Implement views, which are Python functions or classes responsible for
processing incoming HTTP requests, interacting with the database through models,
and returning HTTP responses.
• Controller (Business Logic): Django's views act as controllers in the MVC pattern,
handling the business logic of the application by processing requests, validating
input, and generating responses.
• URL Routing: Define URL patterns in the URLconf (URL configuration) to map
incoming URLs to views. Django's URL routing mechanism allows for clean and
flexible URL patterns.
• Middleware: Implement middleware components to process requests and
responses at various stages of the Django request/response cycle. Middleware can
perform tasks such as authentication, session management, and error handling.

Front-end Development:

• Templates: Create HTML templates using Django's template engine, which allows
for the dynamic generation of HTML content based on data provided by views.
• Static Files Handling: Serve static files (e.g., CSS, JavaScript, images) using Django's
built-in static files handling capabilities. Static files are typically stored in the
project's static directory.
• Integration with Front-end Frameworks: Optionally integrate Django with front-end
frameworks like React.js, Vue.js, or Angular for building rich, interactive user
interfaces. Django can serve as a RESTful API backend while the front-end
framework handles the UI rendering and user interactions.

Database Interaction:

Django supports multiple databases including PostgreSQL, MySQL, SQLite, and Oracle.
Developers can define database models using Django's ORM and perform database
operations such as querying, inserting, updating, and deleting records.

Authentication and Authorization:

Implement user authentication and authorization using Django's built-in authentication


system. Django provides tools for user management, password hashing, session
management, and permissions handling out of the box.

Deployment and Scaling:

MALLIKARJUNA GD Page10 | 280


21CS62 Course Title : Fullstack Development

Deploy Django applications to production servers using platforms like Heroku, AWS, or
DigitalOcean. Django applications can be scaled horizontally by adding more application
instances behind a load balancer to handle increased traffic.

1.2 INSTALLATION
Open Terminal or Command Prompt:

Open a terminal or command prompt on your system.

Install Python (if not already installed):

If Python is not installed on your system, you need to install it first. You can download Python
from the official website: python.org. Follow the installation instructions provided for your
operating system.

Verify Python Installation:

After installing Python, verify that it's installed correctly by opening the terminal or
command prompt and typing:

python --version

This command should display the installed Python version.

Virtual Environment

A virtual environment is a self-contained directory tree that contains a Python installation


for a particular version of Python, plus a number of additional packages. It allows you to have
multiple isolated Python environments on a single machine, each with its own Python
interpreter and set of installed packages.

The purpose of using a virtual environment, especially when working with Django, includes:

Isolation: Virtual environments provide isolation between different projects and their
dependencies. This means that each project can have its own set of dependencies without
affecting other projects or the system-wide Python installation. This helps avoid conflicts
between different versions of packages and ensures that each project remains self-
contained and independent.

Dependency Management: By using a virtual environment, you can easily manage


dependencies for your Django project. You can specify the exact versions of packages
required for your project, ensuring that it works consistently across different environments
and preventing unexpected issues due to dependency changes.

Reproducibility: Virtual environments make it easier to reproduce the development


environment for your Django project on other machines. By sharing the project's

MALLIKARJUNA GD Page11 | 280


21CS62 Course Title : Fullstack Development

requirements.txt file (which lists all dependencies), other developers can quickly create the
same environment using the same versions of packages.

Sandboxing: Virtual environments provide a sandboxed environment where you can install
and experiment with different packages and versions without affecting the global Python
installation or other projects. This allows for easy experimentation and testing of new
libraries or features without risking the stability of other projects.

Deployment: When deploying your Django project to a production server, using a virtual
environment ensures that the server environment matches your development environment
closely. This helps minimize deployment issues and ensures that your project runs smoothly
in the production environment.

To create and activate a virtual environment for a Django project, you can use Python's built-
in venv module or third-party tools like virtualenv or pipenv. Once activated, you can install
Django and other project dependencies within the virtual environment using pip.

Overall, using a virtual environment for Django development is considered a best practice
and helps maintain a clean and organized development environment while ensuring
consistency, reproducibility, and isolation of dependencies.

py -m venv myworld

This will set up a virtual environment, and create a folder named "myworld" with subfolders
and files, like this:

Then you have to activate the environment, by typing this command:

myworld\Scripts\activate.bat

Install Django:

Now, you can use pip to install Django. In the terminal or command prompt, type:

pip install django

This command will download and install the latest version of Django from the Python
Package Index (PyPI) along with its dependencies.

Verify Django Installation:

MALLIKARJUNA GD Page12 | 280


21CS62 Course Title : Fullstack Development

After installing Django, you can verify the installation by running the following command:

django-admin --version

This command should display the installed Django version.

Create a Django Project:

Now that Django is installed, you can create a new Django project. Navigate to the directory
where you want to create the project and run:django-admin startproject myproject`

Replace "myproject" with the name you want to give your project.

Run the Development Server:

Navigate into the newly created project directory:

cd myproject

Then start the development server by running:

python manage.py runserver

This command will start the Django development server, and you should see output
indicating that the server is running.

Access the Django Admin Interface:

Open a web browser and go to http://127.0.0.1:8000/admin/. You should see the Django
admin login page.

MALLIKARJUNA GD Page13 | 280


21CS62 Course Title : Fullstack Development

That's it! You've now installed Django from scratch using pip and created a new Django
project. You can continue developing your project by following the Django documentation
and tutorials.

1.3 WEB FRAMEWORK


A web framework is a software framework that provides a structure and set of tools to
facilitate the development of web applications. Web frameworks typically include libraries,
modules, and pre-written code that abstract away common tasks, allowing developers to
focus on building application-specific functionality rather than dealing with low-level details.

Key components and features of web frameworks:

• Routing: Web frameworks provide mechanisms for mapping URLs to specific code
functions or classes, known as routes. This allows developers to define how different
URLs should be handled by the application.
• HTTP Request Handling: Web frameworks handle incoming HTTP requests from
clients (e.g., web browsers) and provide facilities for parsing request data, such as
form submissions, query parameters, and request headers.
• HTTP Response Generation: Web frameworks facilitate the generation of HTTP
responses to send back to clients. This includes rendering HTML templates,
serializing data into various formats (e.g., JSON, XML), and setting response headers.
• Template Engine: Many web frameworks include a template engine that enables
developers to generate dynamic HTML content by combining static HTML templates
with dynamic data provided by the application.
• Database Interaction: Web frameworks often include libraries or modules for
interacting with databases, such as ORM (Object-Relational Mapping) systems that
map database tables to application objects and provide an abstraction layer for
database operations.
• Middleware: Middleware components intercept HTTP requests and responses,
allowing developers to perform common tasks such as authentication, logging, error
handling, and request/response modification in a modular and reusable way.
• Security Features: Web frameworks provide features to help developers address
common security concerns, such as protection against CSRF (Cross-Site Request
Forgery) attacks, XSS (Cross-Site Scripting) prevention, input validation, and secure
session management.
• Session Management: Web frameworks typically include mechanisms for managing
user sessions, such as storing session data on the server or using client-side cookies
to maintain session state.
• Authentication and Authorization: Many web frameworks include built-in support
for user authentication and authorization, allowing developers to secure access to
application resources based on user roles and permissions.

MALLIKARJUNA GD Page14 | 280


21CS62 Course Title : Fullstack Development

• Testing Support: Web frameworks often provide tools and utilities for writing and
running automated tests to ensure the correctness and reliability of web
applications.

Examples of popular web frameworks include Django (Python), Flask (Python), Ruby on Rails
(Ruby), Express.js (Node.js), Laravel (PHP), Spring Boot (Java), and ASP.NET Core (C#). Each
framework has its strengths, features, and ecosystem, catering to different programming
languages and development preferences.

1.4 MVC DESIGN PATTERN


The Model-View-Controller (MVC) design pattern is a widely used architectural pattern for
developing user interfaces in software applications. It divides the application into three
interconnected components: Model, View, and Controller. Let's delve into the relationship
and details of each component within the MVC architecture:

Model:

Responsibility: The Model component represents the application's data and business logic.
It encapsulates the data structure and logic for manipulating that data.

Characteristics:

• It does not depend on the user interface or presentation layer.

MALLIKARJUNA GD Page15 | 280


21CS62 Course Title : Fullstack Development

• It typically interacts with the database, file system, web services, or other data
sources to retrieve and manipulate data.
• It notifies the View component of any changes in the data (often through events or
observers).

Example: In a web application, the Model might consist of classes representing entities like
User, Product, or Order, along with logic for database operations like CRUD (Create, Read,
Update, Delete).

View:

Responsibility: The View component is responsible for presenting the data to the user and
gathering user input. It represents the user interface (UI) of the application.

Characteristics:

• It receives data from the Model and renders it in a format suitable for the user (e.g.,
HTML for web applications, GUI elements for desktop applications).
• It does not contain business logic; its primary role is to display data and handle user
interactions.
• It may send user input (e.g., form submissions, button clicks) to the Controller for
processing.

Example: In a web application, the View component comprises HTML templates, CSS
stylesheets, and client-side scripts (e.g., JavaScript) responsible for rendering dynamic
content and handling user interactions.

Controller:

Responsibility: The Controller component acts as an intermediary between the Model and
the View. It receives user input from the View, processes it (possibly involving interactions
with the Model), and updates the View accordingly.

Characteristics:

• It interprets user actions and translates them into operations on the Model.
• It updates the View based on changes in the Model and handles user interactions by
invoking appropriate actions.
• It typically contains application logic related to routing, request handling, and
business workflow orchestration.

Example: In a web application, the Controller component consists of server-side code (e.g.,
servlets, controllers in MVC frameworks like Spring MVC or Django) responsible for handling
HTTP requests, interacting with the Model to perform business operations, and selecting the
appropriate View to render.

MALLIKARJUNA GD Page16 | 280


21CS62 Course Title : Fullstack Development

Relationship:

The Model component interacts with the View indirectly through the Controller. It notifies
the Controller of any changes in the data, which in turn updates the View.

The View component can send user input (e.g., form submissions, and button clicks) to the
Controller for processing.

The Controller component communicates with both the Model and the View. It retrieves
data from the Model, processes user input, and updates the View based on the changes in
the Model.

Overall, the MVC pattern promotes the separation of concerns, making it easier to maintain,
test, and evolve software applications by decoupling the user interface, data, and application
logic.

1.5 DJANGO EVOLUTION


Django is a high-level Python Web framework that encourages rapid development and clean,
pragmatic design.

Versio Releas
n e Year Key Features
0.9 2005 Initial public release

0.91 2006 Improved admin interface, new template filters

0.95 2006 Form library overhaul, enhanced documentation

0.96 2006 Session framework, generic views

1 2008 Stability guarantees, long-term support (LTS)

1.1 2009 Aggregates support, GeoDjango, improved testing

1.2 2010 Multiple database support, CSRF protection

1.3 2011 Class-based views, improved static files handling

1.4 2012 Time zone support, custom user model

1.5 2013 Custom template tags, configurable user model

1.6 2013 Improved testing tools, connection pooling

MALLIKARJUNA GD Page17 | 280


21CS62 Course Title : Fullstack Development

1.7 2014 Migrations framework, application loading refactor

1.8 2015 Built-in support for multiple template engines

1.9 2015 Automatic password validation, admin list filters

1.1 2016 Template-based widget rendering, conditional expressions

1.11 2017 Longer-term support, subquery expressions

2 2017 Python 3 only, new URL syntax, window expressions

2.1 2018 PostgreSQL 9.4+ JSONField support, easier testing

2.2 2019 Advanced options for database indexes, performance improvements

3 2019 ASGI support, MariaDB support, timezone-aware datetimes

3.1 2020 Support for customizing form rendering, asynchronous views

3.2 2021 Features new database backends, improved admin customization

Psycopg 3
4.2 2023 support, ENGINE as django.db.backends.postgresql sup
ports both libraries.

5.0 2024 Django 5.0 supports Python 3.10, 3.11, and 3.12.

Key Features:

Django is a powerful web framework for building web applications quickly and efficiently.
Some key features that make Django popular among developers:

Batteries-Included: Django follows the "batteries-included" philosophy, providing a


comprehensive set of built-in features and tools for web development out of the box. This
includes an ORM (Object-Relational Mapping) system for database interaction, a powerful
admin interface, URL routing, authentication and authorization mechanisms, form handling,
and more.

MALLIKARJUNA GD Page18 | 280


21CS62 Course Title : Fullstack Development

Model-View-Controller (MVC) Architecture: Django follows the Model-View-Controller


(MVC) architectural pattern, although it's often described as a "Model-View-Template"
(MVT) framework. This separation of concerns makes it easier to organize code,
maintainability, and scale applications.

ORM (Object-Relational Mapping): Django's ORM simplifies database interactions by


allowing developers to work with database models using Python objects. This abstraction
layer handles database queries, transactions, and migrations, making it easier to manage
database operations and maintain data consistency.

Admin Interface: Django provides a built-in admin interface that allows developers to
create, read, update, and delete database records without writing custom admin views. The
admin interface is highly customizable and can be tailored to suit specific application needs.

URL Routing: Django's URL routing system maps URLs to view functions or classes, allowing
developers to define how different URLs should be handled by the application. This provides
a clean and flexible way to organize application URLs and route requests to appropriate
views.

Template Engine: Django's template engine enables developers to generate dynamic HTML
content by combining static HTML templates with data provided by views. Templates
support template inheritance, template tags, filters, and other features for building modular
and reusable templates.

Security Features: Django prioritizes security and provides built-in protection against
common web vulnerabilities such as CSRF (Cross-Site Request Forgery), XSS (Cross-Site
Scripting), and SQL injection. Django's authentication system, authorization mechanisms,
and session management features help developers implement secure user authentication
and authorization.

ORM Migrations: Django's migration system automates the process of database schema
changes, making it easier to evolve the database schema over time without manual
intervention. Migrations track changes to database models and generate SQL scripts to apply
those changes to the database.

Internationalization and Localization: Django supports internationalization (i18n) and


localization (l10n) features, allowing developers to create multilingual web applications.
Django provides tools for translating text strings, formatting dates, numbers, and handling
language-specific content.

Scalability and Performance: Django is designed to scale well and can handle high traffic
loads efficiently. It offers features like caching, session management, and support for
distributed architectures to improve performance and scalability.

MALLIKARJUNA GD Page19 | 280


21CS62 Course Title : Fullstack Development

These key features, along with Django's emphasis on simplicity, flexibility, and productivity,
make it a popular choice for building a wide range of web applications, from small personal
projects to large-scale enterprise systems.

1.6 PROJECT STRUCTURE


django-admin startproject mytest
This will create a "myproject" folder with the following structure

In Django, project structure typically follows a specific convention, which helps maintain
consistency and organization across projects. Here's a breakdown of the common structure:

Project Directory: This is the main directory for your Django project. It contains everything
related to your project.

Manage.py: This is a command-line utility that lets you interact with your Django project.
You can use it for various tasks like running a development server, creating database
migrations, etc.

# manage.py

import os

import sys

def main():

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

MALLIKARJUNA GD Page20 | 280


21CS62 Course Title : Fullstack Development

from django.core.management import execute_from_command_line

execute_from_command_line(sys.argv)

if __name__ == '__main__':

main()

• os.environ.setdefault: Sets the default settings module for the project.


• execute_from_command_line: Executes Django's command-line utility

requirements.txt: Lists the Python packages required for your project, which can be
installed using pip.

pip install -r requirements.txt

Example Content:

Django==4.0.3

djangorestframework==3.13.1

psycopg2-binary==2.9.3

Django: The main Django framework.

djangorestframework: A powerful and flexible toolkit for building Web APIs.

psycopg2-binary: A PostgreSQL adapter for Python.

Settings.py: This file contains all the configuration settings for your Django project. It
includes settings like database configuration, static files configuration, middleware, installed
apps, etc.

# settings.py

import os

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'your-secret-key'

DEBUG = True

ALLOWED_HOSTS = []

INSTALLED_APPS = [

'django.contrib.admin',

MALLIKARJUNA GD Page21 | 280


21CS62 Course Title : Fullstack Development

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'myapp', # Add your app here

MIDDLEWARE = [

'django.middleware.security.SecurityMiddleware',

ROOT_URLCONF = 'myproject.urls'

TEMPLATES = [

'BACKEND': 'django.template.backends.django.DjangoTemplates',

'DIRS': [BASE_DIR / 'templates'],

'APP_DIRS': True,

'OPTIONS': {

'context_processors': [

'django.template.context_processors.debug',

'django.template.context_processors.request',

'django.contrib.auth.context_processors.auth',

'django.contrib.messages.context_processors.messages',

],

},

},

MALLIKARJUNA GD Page22 | 280


21CS62 Course Title : Fullstack Development

WSGI_APPLICATION = 'myproject.wsgi.application'

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.sqlite3',

'NAME': BASE_DIR / 'db.sqlite3',

AUTH_PASSWORD_VALIDATORS = [

'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',

},

'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',

},

'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',

},

'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',

},

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

STATIC_URL = '/static/'

MALLIKARJUNA GD Page23 | 280


21CS62 Course Title : Fullstack Development

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

BASE_DIR: The base directory of the project.

SECRET_KEY: A secret key for cryptographic signing.

DEBUG: Turns on/off debug mode.

INSTALLED_APPS: Lists all Django applications that are activated in this project.

MIDDLEWARE: Lists middleware components to use.

DATABASES: Database configuration.

TEMPLATES: Configuration for template rendering.

STATIC_URL: URL to use when referring to static files.

URLs.py: This file contains URL patterns for your project. It maps URL paths to views.

# urls.py

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path('admin/', admin.site.urls),

path('', include('myapp.urls')),

path: Used to define URL patterns.

include: Allows referencing other URL configurations.

Wsgi.py: This file is the entry point for WSGI-compatible web servers("Web Server Gateway
Interface.") to serve your Django application.

# wsgi.py

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

application = get_wsgi_application()

get_wsgi_application: Returns a WSGI callable.

MALLIKARJUNA GD Page24 | 280


21CS62 Course Title : Fullstack Development

Asgi.py: This file is similar to Wsgi.py but is used for ASGI-compatible("Asynchronous Server
Gateway Interface.") web servers, which are used for asynchronous applications.

# asgi.py

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

application = get_asgi_application()

get_asgi_application: Returns an ASGI callable.

Application Directory (e.g., myapp)

__init__.py : Marks the directory as a Python package. Typically empty, but can be used to
set up package-level variables or imports.

Example Content: Typically empty

Apps: Django applications are organized into individual apps. Each app typically represents
a specific functionality of your project. Each app has its own models, views, URLs, and
templates.

Configures the application

# apps.py

from django.apps import AppConfig

class MyappConfig(AppConfig):

default_auto_field = 'django.db.models.BigAutoField'

name = 'myapp'

Models: This directory contains Python classes that represent your data models. Each model
typically maps to a database table.

# models.py

from django.db import models

class MyModel(models.Model):

name = models.CharField(max_length=100)

description = models.TextField()

MALLIKARJUNA GD Page25 | 280


21CS62 Course Title : Fullstack Development

def __str__(self):

return self.name

models.Model: Base class for all models.

CharField: A string field for small-to-large-sized strings.

TextField: A large text field.

Views: Views contain the logic that processes a user's request and returns a response. They
interact with models to retrieve or manipulate data and render templates to generate HTML
responses.

# views.py

from django.shortcuts import render

from .models import MyModel

def my_view(request):

mymodels = MyModel.objects.all()

return render(request, 'myapp/template.html', {'mymodels': mymodels})

render: Renders a template with a context.

MyModel.objects.all(): Retrieves all instances of MyModel.

URLs: This file defines URL patterns specific to the app.

Templates: Templates are HTML files that define the presentation layer of your application.
They are typically used by views to generate dynamic content.

Static Files: This directory contains static files like CSS, JavaScript, images, etc., which are
served directly by the web server.

static/

myapp/

css/

styles.css

js/

scripts.js

MALLIKARJUNA GD Page26 | 280


21CS62 Course Title : Fullstack Development

Templates: Although each app can have its own templates directory, you may also have a
global templates directory at the project level for templates that are shared across multiple
apps.

Static Files: Similarly, you may have a global static files directory for static files that are
shared across multiple apps.

Migrations/: Django migrations are used to manage changes to your database schema. The
migrations directory contains Python files that define these changes.

# Example migration file: 0001_initial.py

from django.db import migrations, models

class Migration(migrations.Migration):

initial = True

dependencies = []

operations = [

migrations.CreateModel(

name='MyModel',

fields=[

('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False,


verbose_name='ID')),

('name', models.CharField(max_length=100)),

('description', models.TextField()),

],

),

migrations.CreateModel: Operation that creates a new model.

tests.py:Contains tests for the application to ensure the code works as expected.

# tests.py

from django.test import TestCase

from .models import MyModel

MALLIKARJUNA GD Page27 | 280


21CS62 Course Title : Fullstack Development

class MyModelTestCase(TestCase):

def setUp(self):

MyModel.objects.create(name="Test", description="Test description")

def test_model_creation(self):

test_model = MyModel.objects.get(name="Test")

self.assertEqual(test_model.description, "Test description")

TestCase: Base class for tests.

setUp: Creates test data.

assertEqual: Checks that two values are equal.

Static Root: This is the directory where Django collects all the static files from different apps
into a single location during deployment.

Media Root: This is the directory where user-uploaded files are stored. It's configured in
settings.py.

This structure provides a clear separation of concerns and makes it easier to manage and
scale Django projects. Additionally, you can customize this structure to suit the specific
needs of your project

1.7 DJANGO ARCHITECTURE


Django adopts the MVT (Model-View-Template) architecture.

• Model (M): It represents the data layer, handling database interactions and
logic.
• View (V): Views receive requests, process them, and generate responses. They
contain the application's business logic.
• Template (T): Templates are HTML files with embedded Django Template
Language (DTL) code for dynamic content rendering.

While MVT is akin to MVC (Model-View-Controller), Django differs in handling the controller
part. Instead of using separate controllers, Django integrates controller-like functionality
into its templates. This means Django's templates, which combine HTML and DTL, take on
some of the responsibilities traditionally attributed to controllers in MVC design patterns.

MALLIKARJUNA GD Page28 | 280


21CS62 Course Title : Fullstack Development

Model:

• Think of the Model as the data structure or the database of your web
application.
• It represents the data and the logic to interact with the data.
• For example, if you're building a blog, your models might include classes like
Post, Author, Comment, etc.

simple example of a Django model for a blog post:

from django.db import models

class Post(models.Model):

title = models.CharField(max_length=100)

content = models.TextField()

date_posted = models.DateTimeField(auto_now_add=True)

View:

• Views in Django are like the controllers in other frameworks, but with some
differences.
• Views receive requests from users and return responses.
• They contain the logic to process requests and produce responses.
• Views interact with models to retrieve or manipulate data.

For example, a view to display a list of blog posts:

from django.shortcuts import render

from .models import Post

def post_list(request):

MALLIKARJUNA GD Page29 | 280


21CS62 Course Title : Fullstack Development

posts = Post.objects.all()

return render(request, 'blog/post_list.html', {'posts': posts})

Template:

• Templates are like HTML files but with additional Django Template Language
(DTL) for dynamic content.
• They represent the presentation layer of your application.
• Templates render the data provided by views into HTML that's sent to the user's
browser.

For example, a template to display a list of blog posts:

html

<!-- blog/post_list.html -->

<!DOCTYPE html>

<html>

<head>

<title>Blog Post List</title>

</head>

<body>

<h1>Blog Posts</h1>

<ul>

{% for post in posts %}

<li>{{ post.title }}</li>

{% endfor %}

</ul>

</body>

</html>

In summary, Django's MVT architecture separates the concerns of data (Model), logic (View),
and presentation (Template) in a web application. Models handle data and database
interactions, views process requests and generate responses, and templates render HTML
with dynamic content using Django's template language. This separation of concerns helps
in building scalable and maintainable web applications.

MALLIKARJUNA GD Page30 | 280


21CS62 Course Title : Fullstack Development

Benefits of Django Framework:

• Rapid Development: With Django's design, developers can easily work on different
parts of a website simultaneously. Imagine building a house where one team works
on the foundation while another team works on the roof, speeding up the
construction process.
• Loosely Coupled: In Django, the different components are interconnected only
when needed, enhancing the security of the website. It's like storing valuables in a
safe deposit box instead of leaving them out in the open.
• Ease of Modification: Django's architecture allows for changes in one part of the
application without affecting other parts. It's similar to how you can rearrange
furniture in one room without disturbing the layout of the entire house.
• Security: Django prioritizes security by protecting against common threats like click-
jacking and SQL injections. It's like having a strong lock on your front door and
security cameras to safeguard your home.
• Scalability: Django-powered websites can handle increasing numbers of users
without sacrificing performance. Think of it like a stadium that can accommodate
more and more fans without overcrowding or slowing down, just like Spotify, Netflix,
and other popular sites built with Django.

1.8 DJANGO
Create virtual environment

pip install virtualenvwrapper-win

This command installs the virtualenvwrapper-win package using pip. Virtualenvwrapper-win


is a set of extensions to Ian Bicking’s virtualenv tool, providing commands to manage
multiple virtual environments on Windows.

mkvirtualenv mylearn

This command creates a new virtual environment named "mylearn" using


virtualenvwrapper-win. A virtual environment is an isolated Python environment where
dependencies and packages can be installed without affecting the system-wide Python
installation.

workon mylearn

This command activates the virtual environment named "mylearn". When a virtual
environment is activated, any subsequent Python-related commands will use the packages
and dependencies installed within that environment.

pip install Django

MALLIKARJUNA GD Page31 | 280


21CS62 Course Title : Fullstack Development

This command installs the Django web framework within the activated virtual environment.
Django is a high-level Python web framework that encourages rapid development and clean,
pragmatic design.

django-admin --version

This command checks the version of Django installed within the virtual environment. The
django-admin command-line utility is used for various administrative tasks in Django
projects, and the --version flag displays the installed Django version.

Creating A New Project In Django

To start a new Django project, run the command below:

1.django-admin startproject myproject

After we run the command above, it will generate the base folder structure for a Django
project.

Right now, our myproject directory looks like this:

myproject/ <-- higher level folder

|-- myproject/ <-- django project folder

| |-- myproject/

| | |-- __init__.py

| | |-- settings.py

| | |-- urls.py

| | |-- wsgi.py

| +-- manage.py

manage.py: a shortcut to use the django-admin command-line utility. It’s used to run
management commands related to our project. We will use it to run the development
server, run tests, create migrations, and much more.

__init__.py: this empty file tells Python that this folder is a Python package.

settings.py: this file contains all the project’s configurations. We will refer to this file all the
time!

urls.py: this file is responsible for mapping the routes and paths in our project. For example,
if you want to show something in the URL /about/, you have to map it here first.

MALLIKARJUNA GD Page32 | 280


21CS62 Course Title : Fullstack Development

wsgi.py: this file is a simple gateway interface used for deployment.

Now everything is set up and we can run the server using the below command

2.python manage.py runserver

Now open the URL in a Web browser: http://127.0.0.1:8000

and you should see the success page, which means the server is running correctly.

Creating Django Apps : Django project contains many apps within it. An app can’t run without
a project. You can create an app by the following command

2. django-admin startapp articles

This will give us the following directory structure:

myproject/

|-- myproject/

| |-- articles/ <-- our new django app!

| | |-- migrations/

| | | +-- __init__.py

| | |-- __init__.py

| | |-- admin.py

| | |-- apps.py

| | |-- models.py

| | |-- tests.py

| | +-- views.py

| |-- myproject/

| | |-- __init__.py

| | |-- settings.py

| | |-- urls.py

| | |-- wsgi.py

| +-- manage.py

+-- venv

MALLIKARJUNA GD Page33 | 280


21CS62 Course Title : Fullstack Development

So, let’s first explore what each file does:

migrations: here Django stores some files to keep track of the changes you create in the py
file, and to keep the database and the models.py synchronized.

admin.py: this is a configuration file for a built-in Django app called Django Admin.

apps.py: this is a configuration file of the app itself.

models.py: here is where we define the entities of our Web application. The models are
translated automatically by Django into database tables.

tests.py: this file is used to write unit tests for the app.

views.py: this is the file where we handle the request/response cycle of our Web application.

Now that we created our first app, let’s configure our project to use it. Open settings.py file
and find installed_apps block.

settings.py

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'Django.contrib.staticfiles',

‘articles’

Here we have added ‘articles’ in the installed apps section. Now the app is ready to run with
the Django project.

Configuring Database :By default Django project comes with sqlite3 database but you can
customize it to use MySQL or Postgresql as per the requirements.

settings.py

MALLIKARJUNA GD Page34 | 280


21CS62 Course Title : Fullstack Development

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.postgresql_psycopg2',

'NAME': 'blog',

'USER': 'postgres',

'PASSWORD': '**********',

'HOST': 'localhost',

'PORT': 5432,

Now your project is connected with Postgres database and ready to run.

So now, we have learned how the MVT pattern works and the structure of the Django
application along with the database configuration.

Creating App in project in main myproject

python manage.py startapp calc

Running python manage.py startapp calc is a Django command used to create a new Django
app named "calc" within your Django project. The details as below for the command:

python: This is the Python interpreter used to execute the command.

manage.py: This is a script automatically created in the root directory of a Django project
when you create a new project using django-admin startproject <project_name>. It's used
to perform various administrative tasks related to the Django project.

MALLIKARJUNA GD Page35 | 280


21CS62 Course Title : Fullstack Development

startapp: This is a subcommand of manage.py used to create a new Django app within the
project.

calc: This is the name of the Django app being created. In this case, it's named "calc", but
you can replace it with any name you prefer for your app.

When you run python manage.py startapp calc, Django will generate a directory structure
and files for your new app within your project directory. This includes files for models, views,
templates, and other components typical of a Django app. You'll find the newly created
"calc" directory inside your project's directory.

create urls.py

from django.urls import path

from . import views

urlpatterns = [

path('',views.home ,name='home'),

This is a snippet from a Django project's urls.py file, where URL patterns for routing within
the Django application are defined. Following are the details of each statement

from django.urls import path: This line imports the path function from Django's urls module.
The path function is used to define URL patterns for routing within a Django application.

MALLIKARJUNA GD Page36 | 280


21CS62 Course Title : Fullstack Development

from . import views: This line imports the views module from the current directory
(indicated by .). In Django, views are Python functions or classes that handle HTTP requests
and return HTTP responses.

urlpatterns: This is a list that contains URL patterns for routing within the Django application.

path('', views.home, name='home'): This line defines a URL pattern. It consists of three
parts:

• The first argument '' represents the URL pattern itself. In this case, it's an empty
string, indicating that this URL pattern corresponds to the root URL of the
application.
• The second argument views.home refers to the home function (or view) imported
from the views module. This specifies the view that should be called when the
corresponding URL pattern is matched.
• The third argument name='home' is an optional argument that provides a unique
name to the URL pattern. This is useful for referring to the URL pattern in Django
templates or in other parts of the codebase. In this case, the name 'home' is assigned
to this URL pattern.

In summary, this snippet defines a single URL pattern that corresponds to the root URL of
the Django application. When a request is made to the root URL, it will be routed to the
home view function defined in the views.py module. The URL pattern is named 'home' for
easy reference in the Django project.

Views.py

from django.shortcuts import render

from django.http import HttpResponse

# Create your vie:ws here.

def home(request):

return HttpResponse("WELCOME TO HELLO WORLD")

This is a snippet from a Django application's views.py file, which contains Python functions
or classes that handle HTTP requests and return HTTP responses.

from django.shortcuts import render: This line imports the render function from Django's
shortcuts module. The render function is used to render HTML templates with context data
and return an HttpResponse object.

MALLIKARJUNA GD Page37 | 280


21CS62 Course Title : Fullstack Development

from django.http import HttpResponse: This line imports the HttpResponse class from
Django's http module. The HttpResponse class is used to construct HTTP responses.

def home(request): This line defines a Python function named home that takes a request
object as its argument. In Django, view functions take a request object as input, which
contains information about the HTTP request made by the client.

return HttpResponse("WELCOME TO HELLO WORLD"): This line returns an HttpResponse


object with the string "WELCOME TO HELLO WORLD" as its content. This means that when
the home view function is called in response to an HTTP request, it will return a simple HTTP
response with the specified content.

In summary, this snippet defines a single view function named home that returns a simple
HTTP response with the text "WELCOME TO HELLO WORLD". This view function will be called
when the corresponding URL pattern (defined in the urls.py file) is matched, and it will
generate the HTTP response that is sent back to the client.

Main project:

Urls.py should be modified

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path('',include("calc.urls")),

path('admin/', admin.site.urls),

This snippet is from the main urls.py file in a Django project, which serves as the central
routing configuration for the entire project. Here's an explanation of each part:

from django.contrib import admin: This line imports the admin module from Django's
contrib package, which provides the Django admin interface.

from django.urls import path, include: This line imports the path function and the include
function from Django's urls module. The path function is used to define URL patterns, while
the include function is used to include URL patterns from other Django apps.

urlpatterns: This is a list that contains URL patterns for routing within the Django project.

path('', include("calc.urls")): This line includes URL patterns defined in the urls.py file of the
"calc" Django app. The empty string '' indicates that these URL patterns will be included at

MALLIKARJUNA GD Page38 | 280


21CS62 Course Title : Fullstack Development

the root level of the project. So, any URL matching the root will be directed to the URLs
defined in the "calc" app's urls.py file.

path('admin/', admin.site.urls): This line maps the URL path 'admin/' to the Django admin
interface. When a user visits /admin/ in the browser, they will be directed to the Django
admin interface. The admin.site.urls function includes the admin URLs.

In summary, this urls.py configuration includes the URL patterns defined in the "calc" app's
urls.py file at the root level of the project and also maps the /admin/ URL to the Django
admin interface.

Output:

1.9 VIEWS
In Django, In Django, views are responsible for handling the logic of your web application.
They accept requests and return responses, typically by rendering a template. There are
several types of views you can use in Django:

• Function-Based Views (FBV)


• Class-Based Views (CBV)
• Generic Class-Based Views (GCBV)

1.9.1 Function-based Views (FBVs)


Function-based views are simple Python functions that take an HTTP request as input and
return an HTTP response.

They are defined in views.py file within Django apps.

an example of a function-based view:

from django.http import HttpResponse

def my_view(request):

# Process the request

return HttpResponse("Hello, World!")

Explaination:

MALLIKARJUNA GD Page39 | 280


21CS62 Course Title : Fullstack Development

from django.http import HttpResponse

Line 1: This imports the HttpResponse class from the django.http module. HttpResponse is
a class used to construct HTTP responses in Django.

def my_view(request):

Line 2: This defines a Python function named my_view that takes a request object as its
argument. In Django, views are typically implemented as functions or class-based views. The
request object contains information about the incoming HTTP request.

# Process the request

Line 3: This is a comment line indicating that the subsequent code processes the request.
You would typically put your logic for processing the request here.

return HttpResponse("Hello, World!")

Line 4: This line constructs an HttpResponse object with the content "Hello, World!". This
response will be sent back to the client who made the request. In this case, the response
simply contains the string "Hello, World!".

In summary, the provided code defines a view function named my_view that processes
incoming HTTP requests and returns an HTTP response with the content "Hello, World!".
This is a basic example of how to implement a simple function-based view in Django.

1.9.2 Class-based Views (CBVs)


Class-based views are views implemented as Python classes.

They provide an object-oriented way to define views, making it easier to reuse and organize
code.

Django provides various generic class-based views for common tasks.

an example of a class-based view:

from django.views import View

from django.http import HttpResponse

class MyView(View):

def get(self, request):

# Process GET request

return HttpResponse("Hello, World!")

This code snippet defines a class-based view (CBV) named MyView using Django's class-
based views framework. Here's a breakdown of each part:

MALLIKARJUNA GD Page40 | 280


21CS62 Course Title : Fullstack Development

from django.views import View

from django.http import HttpResponse

Line 1-2: These lines import the View class from django.views module and the HttpResponse
class from django.http module. View is a base class for all class-based views in Django, and
HttpResponse is a class used to construct HTTP responses.

class MyView(View):

Line 3: This line defines a new class named MyView that inherits from the View class. This
means that MyView is a subclass of View, and it inherits all the methods and attributes of
the View class.

def get(self, request):

Line 4: This line defines a method named get within the MyView class. In Django class-based
views, methods like get, post, put, etc., correspond to HTTP request methods. In this case,
get method handles HTTP GET requests.

# Process GET request

Line 5: This is a comment indicating that the subsequent code processes the GET request.
This is where you would typically put your logic for handling the GET request.

return HttpResponse("Hello, World!")

Line 6: This line constructs an HttpResponse object with the content "Hello, World!". This
response will be sent back to the client who made the GET request. In other words, when a
GET request is made to the MyView, it will respond with "Hello, World!".

In summary, the provided code defines a class-based view MyView that handles HTTP GET
requests. When a GET request is made to this view, it responds with an HTTP response
containing the string "Hello, World!". This is a basic example of how to implement a class-
based view in Django to handle GET requests

Modified in Urls.py(in myproject)

from django.urls import path

from .views import home # Import the home view

urlpatterns = [

path('',home.as_view() ,name='home'), # Use home.as_view() for the view

MALLIKARJUNA GD Page41 | 280


21CS62 Course Title : Fullstack Development

This code snippet is from a Django project's urls.py file, where URL patterns for routing
within the Django application are defined.

from django.urls import path

Line 1: This line imports the path function from Django's urls module. The path function is
used to define URL patterns for routing within a Django application.

from .views import home

Line 2: This line imports the home view from the views module in the current directory
(indicated by .). This assumes that there's a module named views.py in the same directory
as the urls.py file, and it contains a view named home.

urlpatterns = [

path('', home.as_view(), name='home'),

Line 3-5: This block defines the urlpatterns list, which contains URL patterns for routing
within the Django application.

path('', home.as_view(), name='home'): This line defines a URL pattern.

• The first argument '' represents the URL pattern itself. In this case, it's an empty
string, indicating that this URL pattern corresponds to the root URL of the
application.
• The second argument home.as_view() refers to the home view imported earlier.
Since home is a class-based view, .as_view() method is used to convert it into a view
callable that Django's URL routing system can use.
• The third argument name='home' is an optional argument that provides a unique
name to the URL pattern. This is useful for referring to the URL pattern in Django
templates or in other parts of the codebase. In this case, the name 'home' is assigned
to this URL pattern.

In summary, this urls.py configuration sets up a single URL pattern that corresponds to the
root URL of the Django application. When a request is made to the root URL, it will be routed
to the home view, which is converted to a view callable using .as_view(). The URL pattern is
named 'home' for easy reference in the Django project.

1.9.3 Generic class based view


Generic Class-Based Views (GCBVs) in Django are a powerful feature that allows developers
to quickly implement common patterns for web applications by providing pre-defined views
for common tasks like displaying a list of objects, handling forms, and processing user input.

MALLIKARJUNA GD Page42 | 280


21CS62 Course Title : Fullstack Development

These views abstract away the repetitive code often written for CRUD (Create, Read, Update,
Delete) operations, making the development process faster and more efficient..

Key Points About Generic Class-Based Views

• Modularity and Reusability: GCBVs promote modularity and code reusability by


encapsulating common behaviors in classes that can be extended and customized.
• Built-In Generic Views: Django provides several built-in generic views such as:

o ListView: Display a list of objects.

o DetailView: Display a detail page for a single object.

o CreateView: Display a form for creating a new object and handle the submission.

o UpdateView: Display a form for updating an existing object and handle the
submission.

o DeleteView: Display a confirmation page for deleting an object and handle the
deletion.

• Customization: While GCBVs offer a lot out-of-the-box, they are also highly
customizable. You can override methods, set attributes, and use mixins to add or modify
functionality according to your application's needs.
• Mixins: Mixins are small reusable pieces of code that can be added to a class to provide
specific functionality. Django provides several mixins that can be combined with GCBVs
to extend their functionality, such as LoginRequiredMixin to restrict access to
authenticated users.

For example:

from django.views.generic import ListView, DetailView

from .models import Item

class ItemListView(ListView):

model = Item

template_name = 'item_list.html'

context_object_name = 'items'

class ItemDetailView(DetailView):

model = Item

template_name = 'item_detail.html'

context_object_name = 'item'

MALLIKARJUNA GD Page43 | 280


21CS62 Course Title : Fullstack Development

In above program, following are the details

• ItemListView is a subclass of ListView.


• model = Item tells the view that it will be working with the Item model.
• template_name = 'item_list.html' specifies the template that will
• ItemDetailView is a subclass of DetailView.
• model = Item tells the view that it will be working with the Item model.
• template_name = 'item_detail.html' specifies the template that will be used to render
the details of a single item.
• context_object_name = 'item' defines the name of the context variable that will be used
in the template to access the details of the item.

1.9.4 Rendering Templates:


Rendering templates in Django involves using the render() function provided by
django.shortcuts to generate HTML content dynamically. This HTML content is typically
based on a template file that contains HTML markup along with template language syntax
for inserting dynamic data.

Here's a step-by-step explanation of how to render templates in Django:

Create a Template File:

First, create a template file (usually with a .html extension) in the templates directory of your
Django app or project. You can organize templates into subdirectories within the templates
directory if needed.

Example template file (my_template.html):

<!DOCTYPE html>

<html lang="en">

<head>

MALLIKARJUNA GD Page44 | 280


21CS62 Course Title : Fullstack Development

<meta charset="UTF-8">

<title>My Template</title>

</head>

<body>

<h1>Hello, {{ name }}!</h1>

</body>

</html>

Define a View Function:

Next, define a view function in your Django app's views.py file. This view function will use
the render() function to render the template with dynamic data.

Example view function:

from django.shortcuts import render

def home(request):

context = {'name': 'Mallikarjuna'}

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

Render the Template in the View:

Within the view function, use the render() function to render the template. Pass the request
object, the name of the template file ('my_template.html' in this case), and a dictionary
containing any dynamic data (context) to be passed to the template.

Example usage of render():

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

Access Dynamic Data in the Template:

In the template file, you can access the dynamic data passed from the view using template
language syntax (usually Django's template tags).

Example usage of dynamic data in the template:

<h1>Hello, {{ name }}!</h1>

Setting.py

MALLIKARJUNA GD Page45 | 280


21CS62 Course Title : Fullstack Development

import os

' DIRS': [os.path.join(BASE_DIR,'templates')]

You can use the os.path.join() function to construct file paths in a platform-independent
way. This function takes multiple path components as arguments and joins them together
using the appropriate path separator for the current operating system.

os.path.join(BASE_DIR, 'templates')

In this example, BASE_DIR is assumed to be a variable containing the base directory of your
Django project. By joining BASE_DIR with 'templates', you create a file path that points to
the templates directory within your project.

The constructed file path can be used in various settings in your Django project, such as
TEMPLATES for specifying the directories where Django should look for templates.

TEMPLATES = [

'BACKEND': 'django.template.backends.django.DjangoTemplates',

'DIRS': [os.path.join(BASE_DIR, 'templates')],

# Other template settings...

},

In this example, the DIRS option specifies a list of directories where Django should look for
template files. By including the file path constructed using os.path.join(), you ensure that
Django will search for templates in the templates directory of your project.

URL Configuration:

Finally, configure the URL patterns in your Django project's urls.py file to map a URL path to
the view function.

Example URL configuration:

from django.urls import path

from .views import home

urlpatterns = [

path('',home ,name='home'),

MALLIKARJUNA GD Page46 | 280


21CS62 Course Title : Fullstack Development

With these steps, when a user accesses the URL path /my-url/ in the browser, Django will
execute the my_view function, render the my_template.html template with the provided
context, and return the resulting HTML content as an HTTP response.

1.9.5 Handling Form Submissions


Views are commonly used to handle form submissions.

They process form data and perform actions such as saving data to the database.

Here's an example of handling form submissions:

from django.http import HttpResponse

from django.shortcuts import render

from .forms import MyForm

def my_form_view(request):

if request.method == 'POST':

form = MyForm(request.POST)

if form.is_valid():

# Process the form data

return HttpResponse("Form submitted successfully!")

else:

form = MyForm()

return render(request, 'my_form_template.html', {'form': form})

Authentication and Authorization:

Views are used to implement user authentication and authorization logic.

They can restrict access to certain views based on user permissions or roles.

Here's an example of using built-in decorators for authentication:

from django.contrib.auth.decorators import login_required

from django.http import HttpResponse

@login_required

def my_protected_view(request):

return HttpResponse("You're logged in!")

MALLIKARJUNA GD Page47 | 280


21CS62 Course Title : Fullstack Development

These examples illustrate the versatility and importance of views in Django for handling
various aspects of web development, including rendering dynamic content, processing form
submissions, and managing user authentication.

1.10 MAPPING URL TO VIEWS


Mapping URLs to views in Django involves defining URL patterns in the URL configuration
(urls.py) of your Django project or app. These URL patterns specify which views should be
invoked when a particular URL is accessed. Here's how to map URLs to views in Django:

Create a View Function or Class:

First, define a view function or class in your Django app's views.py file. This view will contain
the logic for handling the HTTP request and generating the HTTP response.

Example view function:

from django.http import HttpResponse

def my_view(request):

return HttpResponse("Hello, World!")

Example class-based view:

from django.views import View

from django.http import HttpResponse

class MyView(View):

def get(self, request):

return HttpResponse("Hello, World!")

Define URL Patterns:

Next, define URL patterns in your Django project's or app's urls.py file. Each URL pattern is a
mapping between a URL pattern (expressed as a regular expression) and a view function or
class.

Example URL configuration (urls.py):

from django.urls import path

from .views import my_view, MyView

urlpatterns = [

path('hello/', my_view, name='hello'),

MALLIKARJUNA GD Page48 | 280


21CS62 Course Title : Fullstack Development

path('hello-class/', MyView.as_view(), name='hello-class'),

Include App URLs in Project URLs (if applicable):

If you're defining URLs in an app, make sure to include the app's URLs in the project's URL
configuration (urls.py). This is done using the include() function from django.urls.Example
project URL configuration (urls.py):

from django.urls import path, include

urlpatterns = [

path('myapp/', include('myapp.urls')),

# Other URL patterns...

Access Views via URLs:

Once the URL patterns are defined, you can access the views by navigating to the
corresponding URLs in your web browser or by making HTTP requests to those URLs
programmatically.

For the view function my_view, you can access it at /hello/ URL.

For the class-based view MyView, you can access it at /hello-class/ URL.

By mapping URLs to views in this way, you can define the structure of your Django project's
URL routing and specify which views should handle incoming HTTP requests for different
URLs.

1.11 WORKING OF DJANGO URL CONFS AND LOOSE COUPLING


1.11.1 URLconfs in Django:
In Django, URLconfs serve as configuration files where you define the mapping between
URLs and views within your project. They allow you to specify how incoming HTTP requests
should be routed to the appropriate view functions or classes for processing.

URLconfs are Python modules that typically reside in the urls.py file of each Django app or
in the project-level urls.py file. You can have multiple URLconfs, each handling a different set
of URL patterns.

URLconfs contain a list of URL patterns defined using Django's urlpatterns variable. Each URL
pattern is defined using the path() or re_path() function, which takes a URL pattern (as a
string or regular expression) and a view function or class as arguments.

MALLIKARJUNA GD Page49 | 280


21CS62 Course Title : Fullstack Development

When Django receives an incoming HTTP request, it traverses through the urlpatterns list in
each URLconf, attempting to match the requested URL against the defined patterns. If a
match is found, Django invokes the corresponding view function or class to handle the
request.

1.11.2. Loose Coupling in Django URLconfs:


• Decoupling of URLs and Views: Django's URLconfs promote loose coupling between
URLs and views, which means they are not tightly interconnected. This separation
allows you to modify the URL structure of your application without impacting the
underlying view logic, and vice versa.
• Modularity: URLconfs enable you to organize your project's URL routing in a modular
and reusable manner. Each app in your Django project can have its own URLconf,
encapsulating the URL patterns specific to that app. This modular approach enhances
code organization and maintainability.
• Flexibility: By decoupling URLs from views, Django allows you to reuse views across
multiple URL patterns or even across different apps within your project. This flexibility
facilitates code reuse and promotes the development of modular, composable
components.
• Scalability: Loose coupling provided by URLconfs makes it easier to scale and extend
your Django project over time. As your project grows, you can add new URL patterns
and views without tightly coupling them to existing components, thus avoiding
unnecessary dependencies and complexities.

Example:

Consider a scenario where you have an e-commerce Django application with multiple apps
such as products, orders, and cart. Each app has its own URLconf (urls.py) where you define
URL patterns specific to that app. For example:

products/urls.py:

from django.urls import path

from . import views

urlpatterns = [

path('products/', views.ProductListView.as_view(), name='product-list'),

path('products/<int:pk>/', views.ProductDetailView.as_view(), name='product-detail'),

orders/urls.py:

MALLIKARJUNA GD Page50 | 280


21CS62 Course Title : Fullstack Development

from django.urls import path

from . import views

urlpatterns = [

path('orders/', views.OrderListView.as_view(), name='order-list'),

path('orders/<int:pk>/', views.OrderDetailView.as_view(), name='order-detail'),

In this example, each app encapsulates its own URL patterns and view logic, promoting loose
coupling between URLs and views and making the application more modular, maintainable,
and scalable.

In summary, Django's URLconfs play a crucial role in facilitating loose coupling between URLs
and views in your project. By separating URL routing from view logic, URLconfs promote
modularity, flexibility, and scalability, making it easier to develop, maintain, and extend
Django applications.

1.12 ERRORS IN DJANGO, WILD CARD PATTERNS IN URLS


In Django, wild card patterns in URLs are implemented using regular expressions, specifically
with the re_path() function or the path() function with a route converter. These wild card
patterns allow you to capture dynamic parts of a URL and pass them as parameters to your
views. However, errors can occur when defining or using these patterns. Let's explore
common errors and how to address them:

1. Incorrect Regular Expression:

If the regular expression used in the URL pattern is incorrect or invalid, Django will raise an
error when processing the URLconf.

Double-check the regular expression syntax and ensure it matches the intended URL pattern.
Common mistakes include missing parentheses, incorrect escape characters, or invalid
quantifiers.

Error: Suppose you intend to match URLs like /articles/2022/ using a regular expression, but
you mistakenly use an invalid syntax in the URL pattern definition.

Example:

# Incorrect URL pattern with invalid regular expression syntax

from django.urls import re_path

from . import views

urlpatterns = [

MALLIKARJUNA GD Page51 | 280


21CS62 Course Title : Fullstack Development

re_path(r'^articles/\d{4}/$', views.article_detail_view),

Solution: Ensure the regular expression syntax is correct. In this case, the correct syntax for
matching four-digit numbers would be \d{4} to match exactly four digit

2. Conflicting URL Patterns:

If you define multiple URL patterns that match the same URL, Django won't know which view
to invoke, resulting in a URLResolverMatch error.

Review your URLconf and ensure that each URL pattern is unique. If necessary, reorganize
your URL patterns or use more specific regular expressions to avoid conflicts.

Error: You define two URL patterns that match the same URL, causing a conflict.

Example:

# Conflicting URL patterns

urlpatterns = [

path('articles/<int:year>/', views.year_archive),

path('articles/<str:slug>/', views.article_detail),

Solution: Review your URL patterns and ensure each one is unique. You might need to use
more specific regular expressions or reorder your patterns to avoid conflicts.

3. Missing Route Converter:

When using the path() function with route converters, forgetting to specify a converter for
a dynamic part of the URL can lead to errors.

Ensure that each dynamic part of the URL defined in the path() function has a corresponding
route converter specified. Common converters include <int:variable_name> for integers,
<str:variable_name> for strings, etc.

Error: Forgetting to specify a route converter for a dynamic part of the URL in the path()
function can lead to errors.

Example:

# Missing route converter

urlpatterns = [

path('articles/<year>/', views.article_detail), # Missing route converter for 'year'

MALLIKARJUNA GD Page52 | 280


21CS62 Course Title : Fullstack Development

Solution: Ensure that each dynamic part of the URL has a corresponding route converter
specified. For example, <int:year> for integers.

4. Unmatched URL Parameters:

If your view function expects URL parameters but doesn't receive them due to mismatched
URL patterns, Django will raise an error indicating missing arguments.

Ensure that your view function signature matches the URL pattern defined in the URLconf.
If the view expects parameters, make sure the corresponding URL pattern captures and
passes those parameters.

Error: Your view function expects URL parameters but doesn't receive them due to
mismatched URL patterns.

Example:

# View expects parameters but doesn't receive them

def article_detail(request, year, month, day):

...

Solution: Make sure the URL pattern captures and passes the required parameters to the
view function. For example, path('articles/<int:year>/<int:month>/<int:day>/',
views.article_detail).

5. Invalid View Function:

If the view function specified in the URL pattern does not exist or is incorrectly referenced,
Django will raise an error indicating that the view is not callable.

Double-check the view function name and import statement in your URLconf. Ensure that
the view function is correctly defined and imported from the appropriate module.

Error: The view function specified in the URL pattern does not exist or is incorrectly
referenced.

Example:

# Incorrect view function name or reference

urlpatterns = [

path('articles/<int:year>/', views.non_existent_view), # Incorrect view function name

MALLIKARJUNA GD Page53 | 280


21CS62 Course Title : Fullstack Development

Solution: Verify the view function name and import statement in your URLconf. Ensure the
view function is correctly defined and imported.

6. Incorrect URL Reverse Lookup:

When using Django's reverse() function to generate URLs based on view names, errors can
occur if the view name is misspelled or not defined.

Check your usage of the reverse() function and verify that the view name provided matches
the name defined in your URLconf. Ensure that the view name is spelled correctly and
consistently.

Error: Errors occur when using Django's reverse() function to generate URLs based on view
names.

Example:

# Incorrect reverse lookup

from django.urls import reverse

url = reverse('incorrect_view_name') # Incorrect view name

Solution: Double-check the view name passed to the reverse() function. Ensure it matches
the name defined in your URLconf and is spelled correctly

7. Missing Import Statements:

For class-based views or views defined in separate modules, forgetting to import the view in
your URLconf can lead to errors when referencing the view.

Double-check your import statements in the URLconf and ensure that all views referenced
in URL patterns are correctly imported from their respective modules.

By addressing these common errors and ensuring the correct usage of wild card patterns in
URLs, you can avoid issues and build robust URL routing in your Django application.

Error: Forgetting to import the view function or class in your URLconf can lead to errors when
referencing the view.

Example:

# Missing import statement for view function

urlpatterns = [

path('articles/<int:year>/', non_existent_views.article_detail), # Missing import for


'non_existent_views'

MALLIKARJUNA GD Page54 | 280


21CS62 Course Title : Fullstack Development

Solution: Ensure all views referenced in URL patterns are correctly imported from their
respective modules.

By addressing these common errors and ensuring the correct usage of wild card patterns in
URLs, you can avoid issues and build robust URL routing in your Django application.

1.13 IMPORTANT IMPORTS


Category Imports

django.urls, django.views, django.shortcuts, django.http,


Core Django Components
django.forms

Database Related django.db, django.db.models, django.db.migrations

Templates and Static Files django.template, django.contrib.staticfiles

Authentication and django.contrib.auth, django.contrib.sessions,


Authorization django.contrib.messages

Admin Interface django.contrib.admin

Internationalization and
django.utils.translation
Localization

Testing django.test

Settings and Configuration django.conf, django.conf.urls

Other Utilities django.core, django.utils

core Django components:

django.urls: This module is responsible for handling URL routing within a Django project. It
allows you to map URLs to views, which are Python functions that handle HTTP requests and
return HTTP responses.

Example:

# urls.py

from django.urls import path

MALLIKARJUNA GD Page55 | 280


21CS62 Course Title : Fullstack Development

from . import views

urlpatterns = [

path('', views.index, name='index'),

path('about/', views.about, name='about'),

Here, path('', views.index, name='index') maps the root URL to the index view function
defined in views.py.

django.views: This module contains various view classes and functions that handle HTTP
requests and return HTTP responses. Views are responsible for processing user input,
querying the database if necessary, and rendering templates to generate HTML responses.

Example:

# views.py

from django.http import HttpResponse

def index(request):

return HttpResponse("Hello, world! This is the index page.")

def about(request):

return HttpResponse("This is the about page.")

django.shortcuts: This module provides a collection of utility functions that simplify


common tasks in Django views, such as rendering templates or generating HTTP responses.

Example:

# views.py

from django.shortcuts import render

def index(request):

return render(request, 'index.html')

django.http: This module contains classes and functions for handling HTTP requests and
responses. It provides various HTTP-related classes like HttpResponse, JsonResponse, etc.,
which are used to construct HTTP responses.

Example:

# views.py

MALLIKARJUNA GD Page56 | 280


21CS62 Course Title : Fullstack Development

from django.http import HttpResponse

def index(request):

return HttpResponse("Hello, world! This is the index page.")

django.forms: This module provides a set of classes for building and processing HTML forms
in Django. It allows you to define forms as Python classes and provides features like field
validation, form rendering, etc.

Example:

# forms.py

from django import forms

class ContactForm(forms.Form):

name = forms.CharField(max_length=100)

email = forms.EmailField()

message = forms.CharField(widget=forms.Textarea)

These are some of the core components in Django that work together to build web
applications efficiently. By utilizing these components effectively, you can create powerful
and scalable web applications with Django.

Django components related to databases:

Database Related django.db, django.db.models, django.db.migrations

django.db: This module provides the basic functionalities for database operations in Django.
It includes classes and functions for managing database connections, executing queries, and
handling transactions.

Example:

from django.db import connection

def my_custom_sql():

with connection.cursor() as cursor:

cursor.execute("SELECT * FROM myapp_mymodel")

row = cursor.fetchone()

return row

MALLIKARJUNA GD Page57 | 280


21CS62 Course Title : Fullstack Development

django.db.models: This module is the heart of Django's ORM (Object-Relational Mapping)


system. It allows you to define database models as Python classes. Each model class
represents a database table, and its attributes represent fields in that table.

Example:

from django.db import models

class MyModel(models.Model):

name = models.CharField(max_length=100)

age = models.IntegerField()

django.db.migrations: This module handles database schema changes over time. Django
migrations allow you to create, apply, and revert changes to your database schema in a
version-controlled manner. It tracks changes to your models and generates SQL migrations
to reflect those changes in the database schema.

Example:

# Generate a migration file

python manage.py makemigrations myapp

# Apply migrations to the database

python manage.py migrate

These components are essential for interacting with databases in Django, enabling you to
define database models, execute database queries, and manage database schema changes
efficiently. They form the foundation for building robust and scalable web applications with
Django.

Django's components related to handling templates and static files:

Templates and Static Files django.template, django.contrib.staticfiles

django.template: This module provides the template engine for Django, allowing you to
create dynamic HTML pages by combining HTML with template tags and variables.
Templates are typically used to generate user-facing content dynamically.

Example:

<!-- template.html -->

<html>

<head>

MALLIKARJUNA GD Page58 | 280


21CS62 Course Title : Fullstack Development

<title>{{ title }}</title>

</head>

<body>

<h1>Hello, {{ user }}!</h1>

</body>

</html>

In this example, {{ title }} and {{ user }} are template variables that will be replaced with actual
values when the template is rendered.

django.contrib.staticfiles: This module helps manage static files (e.g., CSS, JavaScript,
images) in Django projects. It provides utilities to collect, serve, and organize static files for
your web application. Static files are typically used for styling, client-side scripting, and other
resources that don't change dynamically.

Example:

# settings.py

STATIC_URL = '/static/'

STATICFILES_DIRS = [

os.path.join(BASE_DIR, 'static'),

Here, STATIC_URL specifies the base URL for serving static files, and STATICFILES_DIRS lists
directories where Django should look for static files.

These components work together to enable efficient management and rendering of


templates and static files in Django projects. Templates allow you to create dynamic HTML
content, while static files enhance the user experience by providing styling and client-side
scripting. By leveraging these components effectively, you can build web applications with
rich, interactive interfaces.

Django's components related to authentication and authorization:

Authentication and Authorization django.contrib.auth, django.contrib.sessions,


django.contrib.messages

django.contrib.auth: This module provides a robust authentication system for Django


projects. It includes user authentication, permissions, groups, and user management

MALLIKARJUNA GD Page59 | 280


21CS62 Course Title : Fullstack Development

features. It allows users to sign up, log in, log out, reset passwords, and manage their
accounts.

Example:

# views.py

from django.contrib.auth import authenticate, login, logout

def login_view(request):

if request.method == 'POST':

username = request.POST['username']

password = request.POST['password']

user = authenticate(request, username=username, password=password)

if user is not None:

login(request, user)

# Redirect to a success page

else:

# Return an error message

else:

# Display login form

django.contrib.sessions: This module provides session management functionality for Django


projects. Sessions allow you to store user data across multiple requests, enabling features
like user authentication and personalized user experiences.

Example:

# settings.py

INSTALLED_APPS = [

...

'django.contrib.sessions',

MIDDLEWARE = [

MALLIKARJUNA GD Page60 | 280


21CS62 Course Title : Fullstack Development

...

'django.contrib.sessions.middleware.SessionMiddleware',

django.contrib.messages: This module allows you to display messages to users after specific
actions, such as successful login, form submission, or error handling. It provides a way to
communicate with users without storing the message in the session or database.

Example:

# views.py

from django.contrib import messages

def my_view(request):

...

messages.success(request, 'Success message.')

messages.error(request, 'Error message.')

...

These components are crucial for implementing authentication and authorization in Django
projects. They provide the tools necessary to authenticate users, manage sessions, and
communicate with users effectively. By leveraging these components, you can ensure secure
access control and provide a seamless user experience in your Django applications.

Admin module:

Admin Interface django.contrib.admin

The django.contrib.admin module provides a powerful and customizable admin interface for
managing Django models and data. It allows administrators to perform CRUD (Create, Read,
Update, Delete) operations on models through a user-friendly web interface without writing
additional code.

Here's an overview of how to use the Django admin interface:

Registering Models: First, you need to register your models with the admin interface. You
can do this by creating an admin.py file within your app and using the admin.site.register()
function to register your models.

Example:

# admin.py

MALLIKARJUNA GD Page61 | 280


21CS62 Course Title : Fullstack Development

from django.contrib import admin

from .models import MyModel

admin.site.register(MyModel)

Customizing Admin Interface: You can customize the admin interface by creating a subclass
of admin.ModelAdmin and overriding its properties and methods. This allows you to
customize how your models are displayed, filtered, and edited in the admin interface.

Example:

# admin.py

from django.contrib import admin

from .models import MyModel

class MyModelAdmin(admin.ModelAdmin):

list_display = ('name', 'age', 'created_at')

list_filter = ('age',)

search_fields = ('name',)

admin.site.register(MyModel, MyModelAdmin)

Admin Site Configuration: You can also configure the admin site globally by modifying the
admin.site object in your project's urls.py file. This allows you to customize settings such as
the site header, site title, and index title.

Example:

# urls.py

from django.contrib import admin

from django.urls import path

admin.site.site_header = 'My Admin'

admin.site.site_title = 'My Admin Site'

admin.site.index_title = 'Welcome to My Admin Site'

urlpatterns = [

MALLIKARJUNA GD Page62 | 280


21CS62 Course Title : Fullstack Development

path('admin/', admin.site.urls),

Permissions and User Groups: By default, the admin interface is accessible only to
superusers. However, you can create custom user groups and assign permissions to control
access to specific models or actions within the admin interface.

Example:

# admin.py

from django.contrib import admin

from .models import MyModel

class MyModelAdmin(admin.ModelAdmin):

...

admin.site.register(MyModel, MyModelAdmin)

The Django admin interface is a powerful tool for managing data in your Django projects. By
registering models, customizing the admin interface, and configuring permissions, you can
create an intuitive and efficient admin experience for managing your application's data.

Internationalization and Localization:

Internationalization and Localization django.utils.translation

Django provides robust support for internationalization (i18n) and localization (l10n)
through the django.utils.translation module. This module enables developers to build
applications that can be easily translated into multiple languages and localized for various
regions and cultures.

How to use internationalization and localization in Django:

Internationalization (i18n): Internationalization involves making your Django application


capable of displaying content in multiple languages. This process typically involves marking
strings in your code that need to be translated and providing translation files for different
languages.

Example:

# views.py

from django.utils.translation import gettext as _

MALLIKARJUNA GD Page63 | 280


21CS62 Course Title : Fullstack Development

def my_view(request):

message = _("Hello, world!")

return HttpResponse(message)

Translation Strings: To mark strings for translation, you use the gettext() function from
django.utils.translation. This function is often aliased to _ for brevity. All translatable strings
in your code should be wrapped with this function.

Example:

# models.py

from django.db import models

from django.utils.translation import gettext as _

class MyModel(models.Model):

name = models.CharField(_("Name"), max_length=100)

Creating Translation Files: Django provides management commands (makemessages and


compilemessages) to manage translation files. The makemessages command scans your
codebase for translatable strings and generates or updates a .po file for each language.
These .po files contain the original strings and their translations.

Example:

# Generate translation files for English

python manage.py makemessages -l en

# Generate translation files for Spanish

python manage.py makemessages -l es

Localization (l10n): Localization involves adapting your application to different cultural


conventions, such as date formats, time formats, and numerical representations. Django's
localization features handle these aspects automatically based on the user's language
preference.

Example:

# settings.py

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

MALLIKARJUNA GD Page64 | 280


21CS62 Course Title : Fullstack Development

Django uses settings like LANGUAGE_CODE and TIME_ZONE to determine the appropriate
localization settings for each user.

Template Translation: In addition to Python code, you can also translate strings in Django
templates using the {% trans %} template tag.

Example:

<!-- template.html -->

<h1>{% trans "Welcome" %}</h1>

These are the basic steps to implement internationalization and localization in a Django
application. By following these guidelines, you can create applications that are easily
adaptable to different languages and cultural preferences.

Testing django.test

The django.test module provides tools for writing and running tests for Django applications.
Testing is an essential part of the development process, helping ensure that your application
behaves as expected and remains stable across changes.

Here's an overview of how to use django.test for testing your Django applications:

Writing Tests: You can write tests for your Django application by creating test classes that
subclass django.test.TestCase. Each test method within a test class should begin with the
word "test" to be discovered and executed by the test runner.

Example:

# tests.py

from django.test import TestCase

from myapp.models import MyModel

class MyModelTestCase(TestCase):

def test_something(self):

obj = MyModel.objects.create(name='Test')

self.assertEqual(obj.name, 'Test')

Test Fixtures: You can set up initial data for your tests using fixtures. Fixtures are pre-defined
data sets that are loaded into the database before running tests.

Example:

MALLIKARJUNA GD Page65 | 280


21CS62 Course Title : Fullstack Development

// myapp/fixtures/initial_data.json

"model": "myapp.mymodel",

"pk": 1,

"fields": {

"name": "Test"

Running Tests: You can run tests using the manage.py test command. By default, this
command searches for test modules (files named tests.py or test*.py) in your applications
and runs all test cases found.

Example:

python manage.py test

Testing Views: You can test views by simulating HTTP requests and checking the responses
using test client provided by Django.

Example:

# tests.py

from django.test import TestCase, Client

from django.urls import reverse

class MyViewTestCase(TestCase):

def test_view(self):

client = Client()

response = client.get(reverse('my_view'))

self.assertEqual(response.status_code, 200)

MALLIKARJUNA GD Page66 | 280


21CS62 Course Title : Fullstack Development

Test Coverage: It's important to aim for good test coverage to ensure that all parts of your
application are tested. Tools like coverage.py can be used to measure test coverage and
identify areas that need more testing.

Example:

coverage run --source='.' manage.py test

coverage report

By writing tests with django.test, you can verify that your Django application functions
correctly, identify and fix bugs early in the development process, and maintain confidence
in the stability of your codebase.

Settings and Configuration:

django.conf, django.conf.urls

django.conf and django.conf.urls are essential modules in Django responsible for managing
settings and URL configurations, respectively.

django.conf: This module provides access to Django's settings. Settings are configurations
that control the behavior of a Django project. They are defined in the settings.py file in the
project's directory and include options such as database configuration, middleware settings,
installed applications, and more.

Example:

# settings.py

DEBUG = True

ALLOWED_HOSTS = ['localhost', '127.0.0.1']

You can access these settings from any part of your Django project by importing
django.conf.settings.

Example:

from django.conf import settings

if settings.DEBUG:

print("Debug mode is enabled.")

django.conf.urls: This module contains functions for configuring URL patterns in a Django
project. It provides the urlpatterns list, which maps URLs to view functions or classes.

MALLIKARJUNA GD Page67 | 280


21CS62 Course Title : Fullstack Development

Example:

# urls.py

from django.urls import path

from . import views

urlpatterns = [

path('', views.home, name='home'),

path('about/', views.about, name='about'),

These URL patterns are included in the project's main urls.py file and serve as a routing
mechanism for directing incoming requests to the appropriate view functions or classes.

Example:

# project/urls.py

from django.urls import path, include

urlpatterns = [

path('myapp/', include('myapp.urls')),

In this example, all URLs starting with myapp/ are routed to the myapp.urls module for
further processing.

These modules play a crucial role in configuring and managing the behavior of Django
projects. django.conf allows developers to access and modify project settings, while
django.conf.urls facilitates the organization and routing of URLs within the project.
Understanding and utilizing these modules effectively is essential for building scalable and
maintainable Django applications.

Other Utilities:

django.core, django.utils

In addition to the modules you mentioned, Django provides a wide range of utility modules
within django.core and django.utils to assist in various aspects of web development. Here
are some notable ones:

MALLIKARJUNA GD Page68 | 280


21CS62 Course Title : Fullstack Development

django.core.cache: This module provides a caching framework for storing and retrieving data
to improve performance. Django supports various cache backends such as in-memory
caching, file-based caching, and database caching.

django.core.validators: This module contains a collection of validation functions that can be


used to validate user input in forms and models. These validators cover common validation
scenarios like email validation, URL validation, integer range validation, etc.

django.core.exceptions: This module defines various exception classes used throughout


Django. It includes exceptions for common error scenarios such as HTTP errors (e.g., 404 Not
Found), database errors, and permission-related errors.

django.utils.timezone: This module provides utilities for working with time zones in Django
applications. It includes functions for converting datetimes between different time zones
and handling daylight saving time.

django.utils.translation: We've discussed this already, but it's worth mentioning again. This
module provides tools for internationalization and localization, allowing developers to
create multi-language applications easily.

django.utils.encoding: This module contains utilities for encoding and decoding data in
Django applications. It includes functions for converting between different character
encodings and handling Unicode data.

django.utils.html: This module provides utilities for working with HTML content in Django
applications. It includes functions for escaping and sanitizing HTML content to prevent cross-
site scripting (XSS) attacks.

django.utils.text: This module provides utilities for working with text data in Django
applications. It includes functions for manipulating strings, such as truncating text,
converting text to lowercase or uppercase, and generating slugs.

These are just a few examples of the many utility modules provided by Django to simplify
web development tasks. By leveraging these modules effectively, developers can build
robust and feature-rich web applications with Django.

1.14 PRACTICE PROGRAMS


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

• Visit the official Python website at https://www.python.org/


• Navigate to the Downloads section and click on the "Download Python" button.
• Choose the latest version of Python for Windows and download the installer
(either 64-bit or 32-bit, depending on your system).

MALLIKARJUNA GD Page69 | 280


21CS62 Course Title : Fullstack Development

• Run the downloaded installer and follow the installation wizard.


• During installation, make sure to check the box that says "Add Python X.X to PATH"
to allow Python to be accessible from the command line.
• Once the installation is complete, open a command prompt and type python --
version to verify that Python is installed correctly.

2. Installation of Visual Studio Code:

• Visit the official Visual Studio Code website at https://code.visualstudio.com/


• Click on the "Download for Windows" button to download the installer.
• Run the downloaded installer and follow the installation wizard.
• After installation, you can launch Visual Studio Code from the Start menu.

3. Installation of Django:

• Open Visual Studio Code.


• Open a new terminal by selecting Terminal > New Terminal from the top menu.
• In the terminal, type the following command to install Django using pip:
• pip install django
• Once Django is installed, you can create a new Django project by navigating to the
directory where you want to create the project and running the following
command:
• django-admin startproject myproject
• Replace myproject with the name of your project.
• Navigate into the newly created project directory:
• cd myproject
• To run the Django development server, use the following command:

python manage.py runserver

Open a web browser and go to http://127.0.0.1:8000/ to see the default Django


homepage.

That's it! You've now installed Python, Django, and Visual Studio Code on your Windows
system and created a new Django project. You can continue developing your Django
project using Visual Studio Code as your code editor.
1.14.2 Creation of virtual environment, Django project, and App should be demonstrated
1. Creation of Virtual Environment:

• First, open a terminal (Command Prompt or PowerShell) on your system.


• Navigate to the directory where you want to create your Django project. You can
use the cd command to change directories.
• Once you're in the desired directory, create a new virtual environment by running
the following command:

MALLIKARJUNA GD Page70 | 280


21CS62 Course Title : Fullstack Development

python -m venv myenv


Replace myenv with the name you want to give to your virtual environment.
• Activate the virtual environment by running the appropriate command based on
your terminal:
• Command Prompt:
myenv\Scripts\activate
.\myenv\Scripts\Activate.ps1

You'll know the virtual environment is activated when you see the environment name
(myenv) in your terminal prompt.

2. Setting Up a Django Project:

With the virtual environment activated, you can now install Django and create a new
project.

Install Django using pip:

pip install django

Once Django is installed, create a new Django project by running the following command:

django-admin startproject myproject

Replace myproject with the name you want to give to your Django project.

Navigate into the newly created project directory:

cd myproject

3. Creation of Django App:

Inside the Django project directory (myproject), you can create Django apps.

To create a new app within your project, run the following command:

python manage.py startapp myapp

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

After creating the app, you can start building your application logic within the app
directory (myapp).

That's it! You've now created a virtual environment, set up a Django project, and created
a Django app within the project. You can continue developing your Django application
within the virtual environment. Remember to activate the virtual environment whenever
you work on your Django project.

MALLIKARJUNA GD Page71 | 280


21CS62 Course Title : Fullstack Development

1.14.3 Develop a Django app that displays the current date and time in the server
1. Create a Django App:

First, ensure you have a Django project set up. If not, create one using django-admin
startproject myproject.

Then, create a new Django app within your project using

python manage.py startapp datetimeapp.

2. Define a View:

Open the views.py file inside your app (datetimeapp/views.py) and define a view function
to handle the request and return the current date and time.

from django.shortcuts import render

from django.http import HttpResponse

import datetime

def current_datetime(request):

now = datetime.datetime.now()

return HttpResponse(f"Current date and time: {now}")

3. Configure URL Routing:

Next, map a URL to the view you just created. Open the urls.py file inside your app
(datetimeapp/urls.py) and define the URL pattern.

from django.urls import path

from . import views

urlpatterns = [

path('', views.current_datetime, name='current_datetime'),

4. Include App URLs in Project URLs:

Include the URLs of your app in the project-level urls.py file to make them accessible. Open
myproject/urls.py and include the app's URLs.

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

MALLIKARJUNA GD Page72 | 280


21CS62 Course Title : Fullstack Development

path('admin/', admin.site.urls),

path('datetime/', include('datetimeapp.urls')),

5. Test Your App:

Start the Django development server using python manage.py runserver and navigate to
http://127.0.0.1:8000/datetime/ in your web browser.

You should see the current date and time displayed on the page.

That's it! You've developed a Django app that displays the current date and time on the
server. You can further customize the display format or add additional functionality as
needed.
1.14.4 Develop a Django app that displays the date and time four hours ahead and four hours
before to offset the current date and time in the server.
1. Create a Django App:
Ensure you have a Django project set up. If not, create one using django-admin
startproject myproject.

Create a new Django app within your project using

python manage.py startapp datetimeapp.

2. Define a View:

Open the views.py file inside your app (datetimeapp/views.py) and define a view function
to handle the request and calculate the current date and time, as well as the offset times.

from django.shortcuts import render

from django.http import HttpResponse

import datetime

def datetime_offset(request):

now = datetime.datetime.now()

offset_before = now - datetime.timedelta(hours=4)

offset_after = now + datetime.timedelta(hours=4)

context = {

MALLIKARJUNA GD Page73 | 280


21CS62 Course Title : Fullstack Development

'current_datetime': now,

'datetime_before': offset_before,

'datetime_after': offset_after

return render(request, 'datetimeapp/datetime_offset.html', context)

3. Create a Template:

Create a template file to render the data. Inside your app's directory
(<project>/templates/datetime_offset.html), create a file named datetime_offset.html.

<!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 Offset</title>

</head>

<body>

<h1>Current Date and Time: {{ current_datetime }}</h1>

<h2>Date and Time Four Hours Before: {{ datetime_before }}</h2>

<h2>Date and Time Four Hours After: {{ datetime_after }}</h2>

</body>

</html>

4. Configure URL Routing:

Map a URL to the view you just created. Open the urls.py file inside your app
(datetimeapp/urls.py) and define the URL pattern.

from django.urls import path

from . import views

MALLIKARJUNA GD Page74 | 280


21CS62 Course Title : Fullstack Development

urlpatterns = [

path('', views.datetime_offset, name='datetime_offset'),

5. Include App URLs in Project URLs:

Include the URLs of your app in the project-level urls.py file to make them accessible. Open
myproject/urls.py and include the app's URLs.

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path('admin/', admin.site.urls),

path('datetime/', include('datetimeapp.urls')),

6. settings.py

import os

TEMPLATES = [

'BACKEND': 'django.template.backends.django.DjangoTemplates',

'DIRS': [os.path.join(BASE_DIR,'templates')],

Add – import and DIR with above details

7.Test Your App:

Start the Django development server using python manage.py runserver and navigate to
http://127.0.0.1:8000/datetime/ in your web browser.

You should see the current date and time, along with the date and time four hours ahead
and four hours before displayed on the page.

MALLIKARJUNA GD Page75 | 280


21CS62 Course Title : Fullstack Development

That's it! You've developed a Django app that displays the current date and time along
with the date and time four hours ahead and four hours before. You can further customize
the display format or add additional functionality as needed.

1.15 IMPORTANT NOTE


Answer the following

• Explanation of what a web framework is and its importance in web development.


• Overview of the MVC (Model-View-Controller) design pattern.
• Explanation of the responsibilities of each component in MVC.
• Historical overview of Django's development and evolution.
• Explanation of the typical structure of a Django project.
• Description of directories and files commonly found in a Django project.
• Detailed explanation of Django's architecture.
• Discussion of how Django handles requests and responses.
• Overview of the role of Django's core components such as models, views, and
templates.
• Further exploration of Django's features and capabilities.
• Discussion of Django's built-in functionalities for handling authentication, routing,
forms, etc.
• Explanation of function-based views (FBVs) and class-based views (CBVs).
• Details on rendering templates and handling form submissions.
• Explanation of how URLs are mapped to view functions or classes in Django.
• Discussion of URL patterns and their configuration in Django URLconfs.
• Detailed explanation of URLconfs in Django.
• Discussion on the concept of loose coupling between URLs and views in Django URL
routing.
• Explanation of common errors that can occur in Django URL patterns.
• Discussion on how to handle wild card patterns and resolve errors effectively.

1.16 MCQ
Question 1: What does MVC stand for in the context of web designing?

A) Model-View-Code

B) Model-View-Component

C) Model-View-Controller (Correct)

D) Model-View-Content

Explanation: In MVC architecture, the Model represents data, the View represents the
presentation layer, and the Controller manages user input and updates the model and view
accordingly.

MALLIKARJUNA GD Page76 | 280


21CS62 Course Title : Fullstack Development

Question 2: Which of the following is NOT a typical directory found in a Django project
structure?

A) settings

B) templates

C) assets (Correct)

D) migrations

Explanation: While settings, templates, and migrations are common directories in a Django
project, "assets" is not typically a predefined directory in Django projects. Assets like CSS,
JavaScript, and images are usually stored within static files directories.

Question 3: What is the primary responsibility of a Controller in the MVC design pattern?

A) Displaying data to the user

B) Managing user input and updating data (Correct)

C) Handling database operations

D) Presenting data in a visually appealing manner

Explanation: The primary responsibility of a Controller in the MVC pattern is to manage user
input and update data in the Model and View accordingly. It acts as an intermediary between
the Model and the View.

Question 4:Which architecture does Django follow?

A) Model-View-Component

B) Model-View-Controller

C) Model-View-Template (Correct)

D) Model-Controller-Template

Explanation: Django follows the Model-View-Template (MVT) architecture, which is similar


to the Model-View-Controller (MVC) pattern but with a slight variation in terminology. In
MVT, the View corresponds to the Controller in MVC.

Question 5: Which of the following is a built-in feature of Django?

A) Authentication

B) URL routing

C) Database management

MALLIKARJUNA GD Page77 | 280


21CS62 Course Title : Fullstack Development

D) All of the above (Correct)

Explanation: Django provides built-in features for authentication, URL routing, database
management, and more. These features are part of what makes Django a comprehensive
web framework.

Question 6: What are the two types of views available in Django?

A) Server-side views and client-side views

B) Template views and content views

C) Function-based views and class-based views (Correct)

D) Static views and dynamic views

Explanation: Django supports two types of views: function-based views (FBVs) and class-
based views (CBVs). FBVs are simple functions that take a request and return a response,
while CBVs are classes that handle HTTP methods like GET and POST.

Question 7:What is the purpose of URLconfs in Django?

A) Defining URL patterns and their mappings to views (Correct)

B) Configuring database connections

C) Managing static files

D) Defining template layouts

Explanation: URLconfs in Django are used to define URL patterns and map them to
corresponding view functions or classes. They define the routing logic of a Django
application.

Question 8:What does loose coupling refer to in Django URLconfs?

A) Tight integration between URLs and views

B) Flexible URL routing without direct dependencies (Correct)

C) Strong coupling between models and views

D) Dependency on third-party libraries

Explanation: Loose coupling in Django URLconfs refers to flexible URL routing without direct
dependencies between URLs and views. This allows for easier maintenance and modification
of URL configurations.

Question 9:Which of the following is NOT a common error in Django URL patterns?

A) Incorrect regular expressions

MALLIKARJUNA GD Page78 | 280


21CS62 Course Title : Fullstack Development

B) Conflicting URL patterns

C) Missing import statements (Correct)

D) Incorrect URL names

Explanation: While incorrect regular expressions, conflicting URL patterns, and incorrect URL
names are common errors in Django URL patterns, missing import statements is not directly
related to URL pattern errors. It is more related to Python module import errors.

Question 10:What do wild card patterns in URLs allow for in Django?

A) Capturing parts of URLs for dynamic routing (Correct)

B) Blocking access to specific URLs

C) Reducing the length of URLs

D) Enforcing strict URL patterns

Explanation: Wild card patterns in URLs allow for capturing parts of URLs for dynamic routing
in Django. This enables the passing of parameters from URLs to view functions or classes.

MALLIKARJUNA GD Page79 | 280


21CS62 Course Title : Fullstack Development

MALLIKARJUNA GD Page80 | 280


21CS62 Course Title : Fullstack Development

MODULE-2: DJANGO TEMPLATES AND MODELS


Django templates and models are two fundamental components of Django web applications,
each serving a distinct purpose in the development process. Let's explore each of them:

Django Templates:

• Django templates are used to generate dynamic HTML content for web pages.
• They are text files containing HTML markup with embedded Django template language
code.
• Template files typically have the extension .html.
• Django's template engine processes these files, replacing template variables, tags, and
filters with actual values.
• Templates allow for the separation of presentation logic from business logic, promoting
cleaner and more maintainable code.
• Template inheritance enables the creation of reusable layouts and the extension of base
templates to create specialized pages.
• Template tags and filters provide additional functionality for conditionals, loops,
formatting, and more.
• Templates are rendered by views and returned as HTTP responses to client requests.

Django Models:

• Django models represent the structure and behavior of data in a Django application.
• They are Python classes that inherit from django.db.models.Model.
• Each model class corresponds to a database table, with attributes representing fields in
the table.
• Django's ORM (Object-Relational Mapping) translates model classes and their
relationships into database schema and queries.
• Models define relationships such as ForeignKey, OneToOneField, and ManyToManyField
to establish connections between data entities.
• Model fields specify the data type and constraints for each attribute, such as CharField,
IntegerField, DateField, etc.
• Django's migration system (manage.py makemigrations and manage.py migrate)
manages changes to the database schema based on model definitions.
• Models encapsulate data access and manipulation logic, providing an object-oriented
interface to interact with the underlying database.
• They support validation, querying, and CRUD (Create, Read, Update, Delete) operations
on data entities.

In summary, Django templates facilitate the generation of dynamic HTML content for web pages,
while Django models define the structure and behavior of data entities in a Django application.
Together, they form the backbone of Django web development, enabling the creation of robust
and scalable web applications.

MALLIKARJUNA GD Page81 | 280


21CS62 Course Title : Fullstack Development

2.1 TEMPLATE SYSTEM BASICS


Django's template system is designed to separate the presentation layer (HTML templates) from
the business logic (Python code) in web applications. This separation allows developers to focus
on designing the user interface without mixing it with the application's backend logic.

Django's default template system is a powerful, easy-to-use templating engine designed to create
dynamic web pages by combining HTML with Django template tags, filters, and variables.

Key Features:

• Template Inheritance: Allows creating a base template that other templates can extend.
• Variables: Embedded using double curly braces {{ }}.
• Tags: For logic control like loops and conditionals using {% %}.
• Filters: Modify variables for display using the pipe | symbol.
• Built-in Template Tags: Include common functions like loops, conditionals, and URL
resolution.

Key Components of a Template System:

Template Language:

• Provides syntax and features for embedding dynamic data.


• Common languages(template engine other than own default Django template language):
Jinja2 (Python), Twig (PHP), Handlebars (JavaScript).

Template Files:

• Files containing the template code.


• Use placeholders or expressions to insert dynamic data.
• Often stored separately from the main application code.

Context:

• The data passed to the template.


• Can be variables, objects, arrays, etc.
• The template engine uses this data to render the final output.

Template Engine:

• The software component that processes templates.


• Replaces placeholders with actual data from the context.
• Produces the final output, such as HTML for web pages.

Syntax :

Django's template syntax consists of special tags, variables, and filters enclosed within

MALLIKARJUNA GD Page82 | 280


21CS62 Course Title : Fullstack Development

{% ... %}, {{ ... }}, and {{ ... | filter }} respectively.

Basic Features:

Project Structure:

myproject/

myapp/

templates/

myapp/

index.html

myproject/

settings.py

Configuring Templates in settings.py:

TEMPLATES = [

'BACKEND': 'django.template.backends.django.DjangoTemplates',

'DIRS': [os.path.join(BASE_DIR, 'templates')],

'APP_DIRS': True,

'OPTIONS': {

'context_processors': [

'django.template.context_processors.debug',

'django.template.context_processors.request',

'django.contrib.auth.context_processors.auth',

'django.contrib.messages.context_processors.messages',

],

},

},

Using Django Templates

MALLIKARJUNA GD Page83 | 280


21CS62 Course Title : Fullstack Development

Basic Template Example

Template (templates/myapp/index.html):

<!DOCTYPE html>

<html>

<head>

<title>{{ title }}</title>

</head>

<body>

<h1>{{ title }}</h1>

<ul>

{% for user in users %}

<li>{{ user }}</li>

{% endfor %}

</ul>

</body>

</html>

View:

from django.shortcuts import render

def index(request):

context = {

'title': 'User List',

'users': ['Sachin', Dhoni, 'Virat']

return render(request, 'myapp/index.html', context)

Template Inheritance

Base Template (templates/base.html):

MALLIKARJUNA GD Page84 | 280


21CS62 Course Title : Fullstack Development

<!DOCTYPE html>

<html>

<head>

<title>{% block title %}My Website{% endblock %}</title>

</head>

<body>

<div id="content">

{% block content %}{% endblock %}

</div>

</body>

</html>

Child Template (templates/myapp/index.html):

{% extends "base.html" %}

{% block title %}Home - My Website{% endblock %}

{% block content %}

<h1>Welcome to My Website</h1>

<p>This is the homepage.</p>

{% endblock %}

Common Template Tags and Filters

Variables : {{ variable_name }}

Hello, {{ name }}!

Control Structures

If statement:

{% if user.is_authenticated %}

Hello, {{ user.username }}!

{% else %}

Hello, Guest!

MALLIKARJUNA GD Page85 | 280


21CS62 Course Title : Fullstack Development

{% endif %}

For loop:

<ul>

{% for item in items %}

<li>{{ item }}</li>

{% endfor %}

</ul>

Filters

Filters modify the display of variables. For example:

{{ name|capfirst }} <!-- Capitalizes the first letter -->

Common filters include:

• date
• time
• length
• lower
• upper
• default

Template Inheritance with Blocks

Base Template (templates/base.html):

<!DOCTYPE html>

<html>

<head>

<title>{% block title %}Default Title{% endblock %}</title>

</head>

<body>

<header>

{% block header %}

<h1>Default Header</h1>

MALLIKARJUNA GD Page86 | 280


21CS62 Course Title : Fullstack Development

{% endblock %}

</header>

<main>

{% block content %}{% endblock %}

</main>

<footer>

{% block footer %}

<p>Default Footer</p>

{% endblock %}

</footer>

</body>

</html>

Child Template (templates/myapp/index.html):

{% extends "base.html" %}

{% block title %}Home{% endblock %}

{% block header %}

<h1>Custom Header</h1>

{% endblock %}

{% block content %}

<p>This is the homepage content.</p>

{% endblock %}

{% block footer %}

<p>Custom Footer Content</p>

{% endblock %}

Template Loading

Django searches for templates in the order specified in the DIRS option in TEMPLATES setting and
the app_name/templates/ directories of installed apps.

MALLIKARJUNA GD Page87 | 280


21CS62 Course Title : Fullstack Development

Benefits of Using a Template System:

Separation of Concerns:

• Keeps HTML separate from application logic.


• Easier to manage and maintain code.

Reusability:

• Common elements can be reused across multiple pages.


• Reduces redundancy and promotes DRY (Don't Repeat Yourself) principles.

Flexibility:

• Templates can be easily modified without changing the underlying logic.


• Dynamic content generation allows for personalized and interactive user experiences.

Efficiency:

• Templates can be precompiled and cached for better performance.


• Faster development cycles by reusing components.

By understanding these basics, you can effectively utilize template systems to create dynamic
and maintainable web applications.

You can render dynamic content in templates using variables passed via a context dictionary.
Let's consider an example:

pip install virtualenvwrapper-win

mkvirtualenv mytest

pip install Django

django-admin --version

django-admin startproject helloproj

django-admin startapp helloapp

modify the setting.py in helloproj

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

MALLIKARJUNA GD Page88 | 280


21CS62 Course Title : Fullstack Development

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'helloapp'

urls.py

from django.contrib import admin

from django.urls import path

from django.urls import include

urlpatterns = [

path('', include('helloapp.urls')),

path('admin/', admin.site.urls),

MALLIKARJUNA GD Page89 | 280


21CS62 Course Title : Fullstack Development

You can render dynamic content in templates using variables passed via a context dictionary.

Views.py

from django.shortcuts import render

from django.http import HttpResponse

# Create your views here.

def my_view(request):

context = {

'username': 'Sachin Tendulkar',

'age': 45,

'is_registered': True

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

In the above example, the context dictionary contains data like username, age, and
is_registered, which can be accessed in the template.

MALLIKARJUNA GD Page90 | 280


21CS62 Course Title : Fullstack Development

create folder templated/my_template.html

<!-- my_template.html -->

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>User Profile</title>

</head>

<body>

<h1>Hello, {{ username }}!</h1>

<p>You are {{ age }} years old.</p>

{% if is_registered %}

<p>Welcome back!</p>

{% else %}

<p>Please register to continue.</p>

{% endif %}

</body>

</html>

The context dictionary passed to the render function contains data that will be available in
the template. Each key-value pair in the context becomes a variable accessible in the template.

py manage.py migrate

Running python manage.py migrate is an essential step when you make changes to your
project's models or when you initially set up your project. It ensures that your database schema
stays in sync with your project's models, preventing inconsistencies and errors when interacting
with the database.

python manage.py runserver

Output:

MALLIKARJUNA GD Page91 | 280


21CS62 Course Title : Fullstack Development

Jinja:
Jinja is a modern and designer-friendly templating language for Python, modeled after Django's
templates. It is used to generate HTML or other text formats with data provided in Python
applications. Jinja allows you to embed dynamic content within your templates and is widely
used in web development, particularly in frameworks like Flask and Django.

Key Features of Jinja


• Template Inheritance: Allows for a base template that other templates can extend,
promoting reuse and consistency.
• Variables: Variables are defined using double curly braces {{ }}.
• Control Structures: Support for loops and conditionals using {% %} syntax.
• Filters: Functions that modify variables for display, applied with the pipe | symbol.
• Macros: Functions that can be reused within templates.
• Blocks: Sections of templates that child templates can override

Setting Up Django TemplatesUsing Jinja with Django

Although Django comes with its own templating system, you can use Jinja2 if you prefer its syntax
and features.

Here’s how you can integrate Jinja2 with Django:

Install Jinja2:

pip install Jinja2

Configure Jinja2 in Django:

Update your settings.py to include Jinja2 as a template backend:

TEMPLATES = [

MALLIKARJUNA GD Page92 | 280


21CS62 Course Title : Fullstack Development

'BACKEND': 'django.template.backends.jinja2.Jinja2',

'DIRS': [os.path.join(BASE_DIR, 'jinja2_templates')],

'APP_DIRS': True,

'OPTIONS': {

'environment': 'your_project.jinja2.environment',

},

},

'BACKEND': 'django.template.backends.django.DjangoTemplates',

'DIRS': [os.path.join(BASE_DIR, 'templates')],

'APP_DIRS': True,

'OPTIONS': {

'context_processors': [

'django.template.context_processors.debug',

'django.template.context_processors.request',

'django.contrib.auth.context_processors.auth',

'django.contrib.messages.context_processors.messages',

],

},

},

Create a Jinja2 environment:

Create a file jinja2.py in your project directory and define the Jinja2 environment:

from jinja2 import Environment, FileSystemLoader

from django.conf import settings

MALLIKARJUNA GD Page93 | 280


21CS62 Course Title : Fullstack Development

def environment(**options):

env = Environment(

loader=FileSystemLoader([os.path.join(settings.BASE_DIR, 'jinja2_templates')]),

**options

env.globals.update({

'static': 'django.templatetags.static',

'url': 'django.urls.reverse',

})

return env

Create Jinja2 templates:

Place your Jinja2 templates in the jinja2_templates directory. Use Jinja2 syntax in these
templates.

By following these steps, you can leverage Jinja2's capabilities while working within the Django
framework.

2.2 USING THE DJANGO TEMPLATE SYSTEM


Django template system involves creating HTML templates that Django can dynamically render
with data passed from views. Here's a guide to using the Django template system:

1. Create Templates:

Create HTML templates in your Django project's template directory. By default, Django looks for
templates in a directory named templates within each app and in the project's templates
directory.

<!-- example_template.html -->

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>{{ page_title }}</title>

</head>

MALLIKARJUNA GD Page94 | 280


21CS62 Course Title : Fullstack Development

<body>

<h1>{{ heading }}</h1>

<p>{{ content }}</p>

</body>

</html>

2. Define Views:

Define views in your Django app's views.py file. Views are Python functions that handle HTTP
requests and return HTTP responses, typically by rendering a template.

# views.py

from django.shortcuts import render

def my_view(request):

context = {

'page_title': 'Welcome to My Website',

'heading': 'Hello, Django!',

'content': 'This is a sample Django template.',

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

3. Render Templates in Views:

Use the render function from django.shortcuts to render templates in views. Pass the
request, template name, and context data as arguments to the render function.

4. Handle URLs:

Map URLs to views in your project's URL configuration (urls.py). Define URL patterns using the
path function and specify the corresponding view function.

# urls.py

from django.urls import path

from .views import my_view

urlpatterns = [

path('my-view/', my_view, name='my_view'),

MALLIKARJUNA GD Page95 | 280


21CS62 Course Title : Fullstack Development

5. Accessing Data in Templates:

Access data passed from views in templates using template variables enclosed within double
curly braces ({{ ... }}). These variables are replaced with actual data when the template is
rendered.

6. Control Flow and Logic:

Use template tags like {% if %}, {% for %}, and {% block %} to add control flow and logic
to your templates. These tags enable you to perform conditional rendering, iterate over lists, and
define template blocks for inheritance.

7. Filters:

Apply filters to template variables using the pipe symbol (|). Filters modify the output of
variables, allowing you to format data, manipulate strings, and perform other transformations.

8. Template Inheritance:

Implement template inheritance to create reusable templates and organize your template
hierarchy effectively. Define a base template with common elements and extend it in child
templates to override specific blocks or add additional content.

By following these steps, you can effectively use the Django template system to create dynamic
and interactive web pages in your Django projects.

2.3 BASIC TEMPLATE TAGS AND FILTERS


Basic template tags and filters in Django's template system allow you to add logic, control flow,
and data manipulation directly within your HTML templates. Let's explore some commonly used
template tags and filters:

2.3.1 Template Tags:

1. {% if %}: Used for conditional rendering. It allows you to display content based on
certain conditions.

{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}!</p>
{% else %}
<p>Please log in to continue.</p>
{% endif %}

2. {% for %}: Used for looping over lists or querysets to display repetitive content.

<ul>
{% for item in items %}

MALLIKARJUNA GD Page96 | 280


21CS62 Course Title : Fullstack Development

<li>{{ item }}</li>


{% endfor %}
</ul>

3. {% block %}: Used in template inheritance to define blocks that child templates can
override.

<!-- base.html -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
2.3.2 Template Filters

1. {{ variable|filter }}: Filters allow you to modify the output of template variables.
Django provides several built-in filters for common tasks.

<!-- Convert variable to uppercase -->


{{ name|upper }}

<!-- Truncate text to a certain length -->


{{ description|truncatewords:20 }}

<!-- Format a date -->


{{ date_created|date:"F j, Y" }}

2. safe: Marks a string as safe HTML, preventing Django from escaping it. Use with
caution to avoid XSS vulnerabilities.

{{ unsafe_html|safe }}

3. length: Returns the length of a list, string, or queryset.

{{ items|length }}

4. first: Returns the first item of a list or queryset.

{{ items.first }}

These are just a few examples of basic template tags and filters in Django. They provide
powerful tools for controlling the presentation of your data and adding dynamic behavior

MALLIKARJUNA GD Page97 | 280


21CS62 Course Title : Fullstack Development

to your HTML templates. You can also create custom template tags and filters to extend
Django's template system further.

2.4 MVT DEVELOPMENT PATTERN


The MVT (Model-View-Template) development pattern is Django's interpretation of the popular
MVC (Model-View-Controller) architectural pattern. It's a way to structure code in web
applications, dividing it into three interconnected components: Models, Views, and Templates.

1. Model:

Models represent the data structure of your application. They encapsulate the data access logic,
including querying, insertion, updating, and deletion operations.

Example: Let's consider a simple model representing a blog post. This model would define
attributes like title, content, author, publication date, etc.

# models.py

from django.db import models

class Post(models.Model):

title = models.CharField(max_length=100)

content = models.TextField()

author = models.ForeignKey(User, on_delete=models.CASCADE)

publication_date = models.DateTimeField(auto_now_add=True)

2. View:

Views handle the presentation logic of your application. They receive HTTP requests from clients,
fetch data from the database using models, perform any necessary processing, and then return
HTTP responses, typically rendered using templates.

Example: Let's create a view to display a list of blog posts.

# views.py

from django.shortcuts import render

from .models import Post

def post_list(request):

posts = Post.objects.all()

return render(request, 'blog/post_list.html', {'posts': posts})

MALLIKARJUNA GD Page98 | 280


21CS62 Course Title : Fullstack Development

3. Template:

Templates handle the user interface of your application. They are HTML files with embedded
template tags and variables that Django replaces with actual values when rendering. Templates
allow you to generate dynamic content and present it to users.

Example: Create a template to display a list of blog posts.

<!-- post_list.html -->

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Blog</title>

</head>

<body>

<h1>Blog Posts</h1>

<ul>

{% for post in posts %}

<li>{{ post.title }} - {{ post.publication_date }}</li>

{% endfor %}

</ul>

</body>

</html>

Model: Defines the structure and behavior of the data in your application. It interacts with the
database to store and retrieve data.

View: Handles the request-response cycle. It receives requests from clients, interacts with
models to fetch data, and then passes that data to templates for rendering.

Template: Defines the presentation layer of your application. It contains HTML markup with
embedded template tags and variables, which are replaced with dynamic data when the
template is rendered.

In summary, the MVT development pattern in Django promotes a clean separation of concerns,
making it easier to manage and maintain complex web applications. Models handle data, views

MALLIKARJUNA GD Page99 | 280


21CS62 Course Title : Fullstack Development

handle logic, and templates handle presentation, allowing for modular, reusable, and
maintainable code

let's create a simple Django example using the MVT (Model-View-Template) pattern. We'll build
a basic blog application with functionality to display a list of blog posts.

1. Create a Django Project and App:

First, create a new Django project and an app within it.

django-admin startproject myblogproject

cd myblogproject

python manage.py startapp blog

2. Define Models:

Define a model for the blog post in the blog/models.py file.

# blog/models.py

from django.db import models

class Post(models.Model):

title = models.CharField(max_length=100)

content = models.TextField()

author = models.CharField(max_length=50)

publication_date = models.DateTimeField(auto_now_add=True)

def __str__(self):

return self.title

3. Create Views:

Create views to handle the request-response cycle in the blog/views.py file.

# blog/views.py

from django.shortcuts import render

from .models import Post

def post_list(request):

MALLIKARJUNA GD Page100 | 280


21CS62 Course Title : Fullstack Development

posts = Post.objects.all()

return render(request, 'blog/post_list.html', {'posts': posts})

4. Create Templates:

Create templates to define the presentation layer in the blog/templates/blog directory.

<!-- blog/templates/blog/post_list.html -->

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Blog</title>

</head>

<body>

<h1>Blog Posts</h1>

<ul>

{% for post in posts %}

<li>{{ post.title }} - {{ post.author }} ({{ post.publication_date|date:"F j, Y" }})</li>

{% endfor %}

</ul>

</body>

</html>

5. Define URLs:

Map URLs to views in the blog/urls.py file.

# blog/urls.py

from django.urls import path

from .views import post_list

urlpatterns = [

path('', post_list, name='post_list'),

MALLIKARJUNA GD Page101 | 280


21CS62 Course Title : Fullstack Development

6. Include App URLs:

Include the app's URLs in the project's main URL configuration in the myblogproject/urls.py file.

# myblogproject/urls.py

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path('admin/', admin.site.urls),

path('', include('blog.urls')),

7. Run Migrations:

Apply database migrations to create the necessary database tables for the models.

python manage.py makemigrations

python manage.py migrate

8. Run the Development Server:

Run the Django development server to see the application in action.

python manage.py runserver

Visit http://127.0.0.1:8000/ in your web browser to see the list of blog posts.

This example demonstrates the basic usage of the MVT pattern in Django to create a simple blog
application. Models define the data structure, views handle the logic, and templates handle the
presentation of the application.

2.5 TEMPLATE LOADING


Template loading in Django refers to how Django finds and loads templates to render when
processing a request. By default, Django looks for templates in specific directories within each
app and in the project's global template directories.

Let's explore how template loading works:

1. Template Directories:

Django searches for templates in the following directories by default:

MALLIKARJUNA GD Page102 | 280


21CS62 Course Title : Fullstack Development

Within each app:

Create a directory named templates within each app directory to store app-specific templates.

Project-wide templates:

Optionally, you can define a global templates directory at the project level.

2. Template Loading:

Django uses a template loader to find and load templates from these directories. The template
loader searches for templates in the specified directories based on the order defined in the
TEMPLATES setting in your project's settings.py file.

3. TEMPLATES Setting:

The TEMPLATES setting in your settings.py file configures how Django handles templates. It
includes a list of template engines and their configurations, as well as options for template
directories and other settings.

Example:

Here's an example of how you might configure the TEMPLATES setting in your settings.py file:

# settings.py

TEMPLATES = [

'BACKEND': 'django.template.backends.django.DjangoTemplates',

'DIRS': [

# List of template directories

os.path.join(BASE_DIR, 'templates'), # Project-wide templates directory

# Additional directories for specific apps, if needed

],

'APP_DIRS': True,

'OPTIONS': {

# Other template engine options

},

MALLIKARJUNA GD Page103 | 280


21CS62 Course Title : Fullstack Development

},

In this example:

'DIRS': Specifies a list of directories where Django will search for templates. You can include the
project-wide templates directory as well as additional directories for specific apps.

'APP_DIRS': Indicates whether Django should look for templates within each app's templates
directory. When set to True, Django automatically searches within the templates directory of
each installed app.

Custom Template Loaders:

You can also define custom template loaders if you need more advanced template loading
behavior, such as loading templates from a database or remote location. Django provides
flexibility to customize template loading to suit your project's needs.

Understanding how template loading works in Django allows you to organize your templates
effectively and control how Django finds and loads them when rendering views.

2.6 TEMPLATE INHERITANCE


Template inheritance in Django allows you to create a base template with common elements
and then extend it in child templates to override specific blocks or add additional content. This
promotes code reusability and helps maintain a consistent layout across multiple pages. Let's
walk through an example of template inheritance

2.6.1. Base Template


Create a base template that defines the overall structure of your website. This template typically
includes the HTML structure, header, footer, and any common elements.

<!-- base.html -->

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>{% block title %}My Website{% endblock %}</title>

</head>

<body>

<header>

MALLIKARJUNA GD Page104 | 280


21CS62 Course Title : Fullstack Development

<h1>Welcome to My Website</h1>

</header>

<nav>

<ul>

<li><a href="/">Home</a></li>

<li><a href="/about/">About</a></li>

<li><a href="/contact/">Contact</a></li>

</ul>

</nav>

<main>

{% block content %}

{% endblock %}

</main>

<footer>

<p>&copy; 2024 My Website</p>

</footer>

</body>

</html>

2.6.2 Child Template


Extend the base template in a child template and override specific blocks with content unique to
that page.

<!-- home.html -->

{% extends 'base.html' %}

MALLIKARJUNA GD Page105 | 280


21CS62 Course Title : Fullstack Development

{% block title %}Home - My Website{% endblock %}

{% block content %}

<h2>Welcome to the Home Page</h2>

<p>This is the content of the home page.</p>

{% endblock %}

In this example:

The {% extends %} tag in the child template (home.html) specifies that it extends the base
template (base.html).

The {% block %} tags define blocks within the base template that can be overridden by child
templates.

In the child template (home.html), we override the title block with "Home - My Website" and the
content block with content specific to the home page.

2.6.3 Render the Child Template:


Render the child template in a Django view as usual.

# views.py

from django.shortcuts import render

def home(request):

return render(request, 'home.html')

output:

When a user visits the home page of your website, Django renders the home.html template,
which extends the base.html template. The content defined in the home.html template is
inserted into the {% block content %} block of the base.html template, resulting in a complete
HTML page with the common layout provided by the base template.

This example demonstrates how to use template inheritance in Django to create reusable
templates and maintain a consistent layout across multiple pages. You can extend this pattern to
create additional child templates for different pages of your website.

2.7 Databases

Django is a high-level Python web framework designed to enable rapid development and clean,
pragmatic design. One of its key features is the integration of an Object-Relational Mapping
(ORM) system, which allows developers to interact with the database using Python code instead

MALLIKARJUNA GD Page106 | 280


21CS62 Course Title : Fullstack Development

of writing raw SQL queries. This abstraction layer simplifies database operations and makes code
more readable and maintainable.

The ORM in Django translates Python classes into database tables and instances of those classes
into rows in the database. This allows developers to use Python code to interact with the
database, making it easier to work with data without needing to write complex SQL queries.

2.7.1 Configuring Databases

The database configuration in Django is done through the settings.py file. This file contains a
DATABASES setting, a dictionary that defines the connection parameters for the database.

Example for SQLite (default):

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.sqlite3',

'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

Example for PostgreSQL:

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.postgresql',

'NAME': 'mydatabase',

'USER': 'mydatabaseuser',

'PASSWORD': 'mypassword',

'HOST': 'localhost',

'PORT': '5432',

MALLIKARJUNA GD Page107 | 280


21CS62 Course Title : Fullstack Development

Example for MySQL:

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.mysql',

'NAME': 'mydatabase',

'USER': 'mydatabaseuser',

'PASSWORD': 'mypassword',

'HOST': 'localhost',

'PORT': '3306',

2.7.2 Defining and Implementing Models

In Django, models are the single, definitive source of information about your data. Each model
maps to a single database table. Defining models in Django involves creating Python classes that
inherit from django.db.models.Model. Each attribute of the class represents a database field.

Here's a detailed breakdown of how to define and implement models in Django:

1. Basic Structure of a Model

A model class is defined in the models.py file of your Django app.

Here's a simple example:

models.py:

from django.db import models

MALLIKARJUNA GD Page108 | 280


21CS62 Course Title : Fullstack Development

class Book(models.Model):

title = models.CharField(max_length=200)

author = models.CharField(max_length=100)

published_date = models.DateField()

isbn = models.CharField(max_length=13, unique=True)

def __str__(self):

return self.title

2. Fields

Each attribute in the model class represents a database field. Django provides a variety of field
types:

1. CharField

CharField is used for small to large-sized strings, and you must specify max_length.

class Author(models.Model):

name = models.CharField(max_length=100)

2. TextField

TextField is used for large text content, such as a blog post or article.

class Article(models.Model):

content = models.TextField()

3. IntegerField

IntegerField is used for storing integer values.

class Product(models.Model):

stock = models.IntegerField()

4. FloatField

FloatField is used for storing floating-point numbers.

class Product(models.Model):

price = models.FloatField()

MALLIKARJUNA GD Page109 | 280


21CS62 Course Title : Fullstack Development

5. DateField

DateField is used for storing dates.

class Event(models.Model):

event_date = models.DateField()

6. DateTimeField

DateTimeField is used for storing date and time.

class Event(models.Model):

start_time = models.DateTimeField()

7. BooleanField

BooleanField is used for storing True/False values.

class Task(models.Model):

completed = models.BooleanField(default=False)

8. ForeignKey

ForeignKey is used for creating many-to-one relationships. It requires an on_delete argument


to specify what happens when the related object is deleted.

class Author(models.Model):

name = models.CharField(max_length=100)

class Book(models.Model):

title = models.CharField(max_length=200)

author = models.ForeignKey(Author, on_delete=models.CASCADE)

9. ManyToManyField

ManyToManyField is used for creating many-to-many relationships..

Example of Different Field Types:

class Author(models.Model):

name = models.CharField(max_length=100)

birth_date = models.DateField()

MALLIKARJUNA GD Page110 | 280


21CS62 Course Title : Fullstack Development

class Publisher(models.Model):

name = models.CharField(max_length=100)

class Book(models.Model):

title = models.CharField(max_length=200)

author = models.ForeignKey(Author, on_delete=models.CASCADE)

publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)

published_date = models.DateField()

isbn = models.CharField(max_length=13, unique=True)

price = models.FloatField()

description = models.TextField()

available = models.BooleanField(default=True)

def __str__(self):

return self.title

3. Field Options

Fields can take various optional arguments:

null: If True, Django will store empty values as NULL in the database.

blank: If True, the field is allowed to be blank.

default: The default value for the field.

choices: A sequence of (value, display) pairs for drop-down choices.

unique: If True, this field must be unique throughout the table.

primary_key: If True, this field is the primary key for the model.

Example with Field Options:

class Book(models.Model):

title = models.CharField(max_length=200, unique=True)

author = models.CharField(max_length=100)

published_date = models.DateField()

isbn = models.CharField(max_length=13, unique=True)

MALLIKARJUNA GD Page111 | 280


21CS62 Course Title : Fullstack Development

genre = models.CharField(max_length=50, choices=[

('fiction', 'Fiction'),

('nonfiction', 'Non-Fiction'),

('scifi', 'Science Fiction'),

('biography', 'Biography'),

])

available = models.BooleanField(default=True)

price = models.FloatField(null=True, blank=True)

def __str__(self):

return self.title

4. Meta Options

Meta options are defined in a nested class Meta within the model. They are used to change the
behavior of the model, like ordering, verbose name, etc.

Example:

class Book(models.Model):

title = models.CharField(max_length=200)

author = models.CharField(max_length=100)

published_date = models.DateField()

isbn = models.CharField(max_length=13, unique=True)

class Meta:

ordering = ['title']

verbose_name = 'book'

verbose_name_plural = 'books'

def __str__(self):

return self.title

5. Model Methods

MALLIKARJUNA GD Page112 | 280


21CS62 Course Title : Fullstack Development

You can define methods on your model to add custom "table-level" functionality to your
models.

Example:

class Book(models.Model):

title = models.CharField(max_length=200)

author = models.CharField(max_length=100)

published_date = models.DateField()

isbn = models.CharField(max_length=13, unique=True)

def __str__(self):

return self.title

def is_recent(self):

return self.published_date >= timezone.now() - datetime.timedelta(days=365)

In this example, is_recent is a custom method that checks if the book was published within the
last year.

6. Relationships

In Django, relationships between models are a crucial aspect of defining the schema for your
database. Django provides several types of fields to define relationships:

1.One-to-One Relationships:

Use the OneToOneField to define a one-to-one relationship. This means that each instance of a
model can be related to one, and only one, instance of another model.

Example:

from django.db import models

class UserProfile(models.Model):

user = models.OneToOneField(User, on_delete=models.CASCADE)

bio = models.TextField()

website = models.URLField()

class User(models.Model):

username = models.CharField(max_length=100)

MALLIKARJUNA GD Page113 | 280


21CS62 Course Title : Fullstack Development

email = models.EmailField()

2. Many-to-One Relationships:

Use the ForeignKey to define a many-to-one relationship. This is the most common type of
relationship, where many instances of a model can be related to one instance of another model.

Example:

class Author(models.Model):

name = models.CharField(max_length=100)

class Book(models.Model):

title = models.CharField(max_length=100)

author = models.ForeignKey(Author, on_delete=models.CASCADE)

3. Many-to-Many Relationships:

Use the ManyToManyField to define a many-to-many relationship. This means that each
instance of a model can be related to many instances of another model, and vice versa.

Example:

class Student(models.Model):

name = models.CharField(max_length=100)

class Course(models.Model):

title = models.CharField(max_length=100)

students = models.ManyToManyField(Student)

4. Self-referential Many-to-Many Relationships:

You can also use ManyToManyField to create self-referential relationships where instances of a
model can be related to other instances of the same model.

Example:

class Person(models.Model):

name = models.CharField(max_length=100)

friends = models.ManyToManyField("self")

5. Custom Through Models for Many-to-Many Relationships:

MALLIKARJUNA GD Page114 | 280


21CS62 Course Title : Fullstack Development

Sometimes, you may need to define extra fields on the relationship model for a many-to-many
relationship. In such cases, you can use the through argument to specify a custom intermediate
model.

Example:

class Student(models.Model):

name = models.CharField(max_length=100)

class Course(models.Model):

title = models.CharField(max_length=100)

students = models.ManyToManyField(Student, through='Enrollment')

class Enrollment(models.Model):

student = models.ForeignKey(Student, on_delete=models.CASCADE)

course = models.ForeignKey(Course, on_delete=models.CASCADE)

date_enrolled = models.DateField()

6. Defining Relationships with Optional Parameters

on_delete Parameter:

This parameter specifies what should happen when the referenced object is deleted. Options
include CASCADE, PROTECT, SET_NULL, SET_DEFAULT, and DO_NOTHING.

author = models.ForeignKey(Author, on_delete=models.CASCADE)

related_name Parameter:

This parameter specifies the name of the reverse relation from the related model back to this
one.

author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')

related_query_name Parameter:

This parameter specifies the name to use for the reverse filter name from the related model
back to this one in queries.

author = models.ForeignKey(Author, on_delete=models.CASCADE,


related_query_name='book')

through_fields Parameter:

MALLIKARJUNA GD Page115 | 280


21CS62 Course Title : Fullstack Development

When using a custom through model, through_fields can specify which fields on the
intermediate model should be used to link it to the two models it connects.

students = models.ManyToManyField(Student, through='Enrollment', through_fields=('course',


'student'))

By leveraging these relationship fields, you can create complex and meaningful relationships
between your Django models, enabling a rich and connected data structure.

2.7.3 Basic Data Access


Django's ORM (Object-Relational Mapping) provides a high-level abstraction for interacting
with your database using Python code. You can perform create, retrieve, update, and delete
operations with ease. Let's go through each of these operations with examples.

1. Creating Records

To create records, you instantiate a model and call the save() method, or use the create()
method.

Using the save() method:

from myapp.models import Author, Book

# Create a new author

author = Author(name='George Orwell', birth_date='1903-06-25')

author.save()

# Create a new book

book = Book(

title=’Mahabharath’,

description=’Mahabharath Epic of 18 days of War',

published_date='2024-06-08',

price=2229.99,

stock=50,

available=True,

author=author

book.save()

MALLIKARJUNA GD Page116 | 280


21CS62 Course Title : Fullstack Development

Using the create() method:

from myapp.models import Author, Book

# Create a new author

author = Author.objects.create(name=’Vedavyasa’, birth_date='1777-07-26')

# Create a new book

book = Book.objects.create(

title='Brave New World',

description='Dystopian novel set in a futuristic World State.',

published_date='1932-08-31',

price=8.99,

stock=30,

available=True,

author=author

2. Retrieving Records

To retrieve records, you can use the all(), get(), filter(), and exclude() methods.

Retrieve all records:

# Get all authors

authors = Author.objects.all()

# Get all books

books = Book.objects.all()

Retrieve a single record:

# Get a single author by primary key

author = Author.objects.get(pk=1)

# Get a single book by title

book = Book.objects.get(title='1984')

MALLIKARJUNA GD Page117 | 280


21CS62 Course Title : Fullstack Development

Retrieve multiple records with filtering:

# Get all books by a specific author

orwell_books = Book.objects.filter(author__name='George Orwell')

# Get all books that are available

available_books = Book.objects.filter(available=True)

# Get all books with a price greater than 10

expensive_books = Book.objects.filter(price__gt=10)

Exclude certain records:

# Get all books that are not available

unavailable_books = Book.objects.exclude(available=True)

3. Updating Records

To update records, you first retrieve them, modify their attributes, and then call the save()
method.

from myapp.models import Book

# Retrieve a book

book = Book.objects.get(pk=1)

# Update the book's price and stock

book.price = 10.99

book.stock = 40

book.save()

You can also use the update() method to update multiple records at once.

# Update all books to be available

Book.objects.all().update(available=True)

# Increase the price of all books by 1

Book.objects.all().update(price=F('price') + 1)

4. Deleting Records

To delete records, you use the delete() method.

MALLIKARJUNA GD Page118 | 280


21CS62 Course Title : Fullstack Development

Delete a single record:

from myapp.models import Book

# Retrieve a book

book = Book.objects.get(pk=1)

# Delete the book

book.delete()

Delete multiple records:

# Delete all books by a specific author

Book.objects.filter(author__name='SWAMY').delete()

# Delete all books that are out of stock

Book.objects.filter(stock=0).delete()

Example: Putting It All Together

Here's a comprehensive example demonstrating create, retrieve, update, and delete


operations:

from myapp.models import Author, Book

# 1. Create

author1 = Author.objects.create(name='J.K. Rowling', birth_date='1965-07-31')

author2 = Author.objects.create(name='J.R.R. Tolkien', birth_date='1892-01-03')

book1 = Book.objects.create(

title='Harry Potter and the Philosopher\'s Stone',

description='Fantasy novel about a young wizard named Harry Potter.',

published_date='1997-06-26',

price=20.00,

stock=100,

available=True,

author=author1

MALLIKARJUNA GD Page119 | 280


21CS62 Course Title : Fullstack Development

book2 = Book.objects.create(

title='The Hobbit',

description='Fantasy novel about the journey of Bilbo Baggins.',

published_date='1937-09-21',

price=15.00,

stock=50,

available=True,

author=author2

# 2. Retrieve

all_authors = Author.objects.all()

all_books = Book.objects.all()

tolkien_books = Book.objects.filter(author__name='J.R.R. Tolkien')

available_books = Book.objects.filter(available=True)

# 3. Update

book_to_update = Book.objects.get(title='The Hobbit')

book_to_update.price = 18.00

book_to_update.save()

Book.objects.filter(author__name='J.K. Rowling').update(stock=120)

# 4. Delete

book_to_delete = Book.objects.get(title='Harry Potter and the Philosopher\'s Stone')

MALLIKARJUNA GD Page120 | 280


21CS62 Course Title : Fullstack Development

book_to_delete.delete()

Author.objects.filter(name='J.K. Rowling').delete()

In this example:

We create authors and books.

We retrieve all authors, all books, books by Tolkien, and available books.

We update the price of "The Hobbit" and the stock of books by Rowling.

We delete the book "Harry Potter and the Philosopher's Stone" and the author Rowling.

These basic data access operations provide a powerful and intuitive way to interact with the
database using Django's ORM.

2.7.3.1 Adding Model String Representations


Adding a string representation to your model in Django is done by defining the __str__ method.
This method returns a string that is a readable representation of the object. This is particularly
useful for identifying objects in the Django admin interface or the Django shell.

Why Add String Representations?

• Admin Interface: When you look at the list of objects in the Django admin interface, the
__str__ method determines what is displayed for each object.
• Shell: When you print objects in the Django shell, the __str__ method determines the output.
• Debugging: Helps to quickly identify objects during debugging.

Example

Here's how you can add string representations to models:

Author Model

Let's say we have an Author model. We want to see the author's name when we view the
author object.

Before Adding __str__:

class Author(models.Model):

name = models.CharField(max_length=100)

birth_date = models.DateField()

After Adding __str__:

MALLIKARJUNA GD Page121 | 280


21CS62 Course Title : Fullstack Development

class Author(models.Model):

name = models.CharField(max_length=100)

birth_date = models.DateField()

def __str__(self):

return self.name

Book Model

For a Book model, we might want to see the book's title.

Before Adding __str__:

class Book(models.Model):

title = models.CharField(max_length=200)

description = models.TextField()

published_date = models.DateField()

price = models.FloatField()

stock = models.IntegerField()

available = models.BooleanField(default=True)

author = models.ForeignKey(Author, on_delete=models.CASCADE)

publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)

isbn = models.CharField(max_length=13, unique=True)

After Adding __str__:

class Book(models.Model):

title = models.CharField(max_length=200)

description = models.TextField()

published_date = models.DateField()

price = models.FloatField()

stock = models.IntegerField()

available = models.BooleanField(default=True)

author = models.ForeignKey(Author, on_delete=models.CASCADE)

MALLIKARJUNA GD Page122 | 280


21CS62 Course Title : Fullstack Development

publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)

isbn = models.CharField(max_length=13, unique=True)

def __str__(self):

return self.title

Publisher Model

For a Publisher model, the publisher's name would be a suitable string representation.

Before Adding __str__:

class Publisher(models.Model):

name = models.CharField(max_length=100)

After Adding __str__:

class Publisher(models.Model):

name = models.CharField(max_length=100)

def __str__(self):

return self.name

Putting It All Together

Here’s the complete example with __str__ methods added to all relevant models:

from django.db import models

class Author(models.Model):

name = models.CharField(max_length=100)

birth_date = models.DateField()

def __str__(self):

return self.name

class Publisher(models.Model):

name = models.CharField(max_length=100)

def __str__(self):

return self.name

MALLIKARJUNA GD Page123 | 280


21CS62 Course Title : Fullstack Development

class Book(models.Model):

title = models.CharField(max_length=200)

description = models.TextField()

published_date = models.DateField()

price = models.FloatField()

stock = models.IntegerField()

available = models.BooleanField(default=True)

author = models.ForeignKey(Author, on_delete=models.CASCADE)

publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)

isbn = models.CharField(max_length=13, unique=True)

def __str__(self):

return self.title

class Genre(models.Model):

name = models.CharField(max_length=50)

def __str__(self):

return self.name

class Profile(models.Model):

user = models.OneToOneField(User, on_delete=models.CASCADE)

bio = models.TextField()

def __str__(self):

return self.user.username

MALLIKARJUNA GD Page124 | 280


21CS62 Course Title : Fullstack Development

Adding a __str__ method to your Django models is a best practice that significantly improves the
readability and manageability of your objects in various contexts, such as the Django admin
interface and the Django shell. It makes your models more intuitive and easier to work with,
especially during debugging and development

2.7.3.2 Schema Evolution


Schema evolution refers to changing the database schema over time. Django handles this
using migrations, which are a way to propagate changes you make to your models
(adding a field, deleting a model, etc.) into your database schema.
Creating Migrations:
Whenever you change your models, create new migrations to reflect those changes.
$ python manage.py makemigrations
Applying Migrations:
To apply the migrations and update your database schema, use the migrate command.
$ python manage.py migrate
Example of Schema Change:
Let's add a genre field to the Book model:
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
published_date = models.DateField()
isbn = models.CharField(max_length=13, unique=True)
genre = models.CharField(max_length=50, null=True) # New field
def __str__(self):
return self.title
After modifying the model, create and apply the migration:
$ python manage.py makemigrations
$ python manage.py migrate

MALLIKARJUNA GD Page125 | 280


21CS62 Course Title : Fullstack Development

Putting It All Together


Here’s a complete example integrating the above concepts.
models.py:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
published_date = models.DateField()
isbn = models.CharField(max_length=13, unique=True)
genre = models.CharField(max_length=50, null=True) # New field

def __str__(self):
return self.title
views.py:
from django.shortcuts import render, get_object_or_404
from .models import Book
def book_list(request):
books = Book.objects.all()
return render(request, 'book_list.html', {'books': books})

def book_detail(request, book_id):


book = get_object_or_404(Book, id=book_id)
return render(request, 'book_detail.html', {'book': book})
urls.py:
from django.urls import path

MALLIKARJUNA GD Page126 | 280


21CS62 Course Title : Fullstack Development

from . import views


urlpatterns = [
path('', views.book_list, name='book_list'),
path('book/<int:book_id>/', views.book_detail, name='book_detail'),
]
Templates (book_list.html and book_detail.html):
book_list.html:
<!DOCTYPE html>
<html>
<head>
<title>Book List</title>
</head>
<body>
<h1>Books</h1>
<ul>
{% for book in books %}
<li><a href="{% url 'book_detail' book.id %}">{{ book.title }}</a></li>
{% endfor %}
</ul>
</body>
</html>
book_detail.html:
<!DOCTYPE html>
<html>
<head>

MALLIKARJUNA GD Page127 | 280


21CS62 Course Title : Fullstack Development

<title>{{ book.title }}</title>


</head>
<body>
<h1>{{ book.title }}</h1>
<p><strong>Author:</strong> {{ book.author }}</p>
<p><strong>Published Date:</strong> {{ book.published_date }}</p>
<p><strong>ISBN:</strong> {{ book.isbn }}</p>
<p><strong>Genre:</strong> {{ book.genre }}</p>
</body>
</html>
By following these steps, you can efficiently configure, define, and interact with
databases in Django, leveraging its powerful ORM and migration system

MALLIKARJUNA GD Page128 | 280


21CS62 Course Title : Fullstack Development

2.8 PRACTICE
2.8.1 Develop A Simple Django App That Displays An Unordered List Of Fruits And An Ordered List Of
Selected Students For An Event
1. Create a Django Project and App:

First, create a new Django project and an app within it.

django-admin startproject event_project

cd event_project

python manage.py startapp event_app

2. Define Models (Optional):

For this simple example, we won't need any models as we'll be displaying static lists. However,
if you want to extend this app later to include dynamic data, you can define models for fruits
and students.

3. Create Views:

Define views to handle the request-response cycle in the event_app/views.py file.

# event_app/views.py

from django.shortcuts import render

def fruit_list(request):

fruits = ['Apple', 'Banana', 'Orange', 'Grapes']

return render(request, 'event_app/fruit_list.html', {'fruits': fruits})

def student_list(request):

students = ['John', 'Emily', 'Michael', 'Sophia']

return render(request, 'event_app/student_list.html', {'students': students})

4. Create Templates:

Create templates to define the presentation layer in the event_app/templates/event_app


directory.

<!-- fruit_list.html -->

<!DOCTYPE html>

<html lang="en">

<head>

MALLIKARJUNA GD Page129 | 280


21CS62 Course Title : Fullstack Development

<meta charset="UTF-8">

<title>Fruit List</title>

</head>

<body>

<h1>List of Fruits</h1>

<ul>

{% for fruit in fruits %}

<li>{{ fruit }}</li>

{% endfor %}

</ul>

</body>

</html>

<!-- student_list.html -->

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Student List</title>

</head>

<body>

<h1>Selected Students for Event</h1>

<ol>

{% for student in students %}

<li>{{ student }}</li>

{% endfor %}

</ol>

MALLIKARJUNA GD Page130 | 280


21CS62 Course Title : Fullstack Development

</body>

</html>

5. Define URLs:

Map URLs to views in the event_app/urls.py file.

# event_app/urls.py

from django.urls import path

from .views import fruit_list, student_list

urlpatterns = [

path('fruits/', fruit_list, name='fruit_list'),

path('students/', student_list, name='student_list'),

6. Include App URLs:

Include the app's URLs in the project's main URL configuration in the event_project/urls.py file.

# event_project/urls.py

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path('admin/', admin.site.urls),

path('event/', include('event_app.urls')),

7. Run Migrations (Optional):

Since we're not using any models in this example, there's no need to run migrations.

8. Run the Development Server:

Run the Django development server to see the application in action.

MALLIKARJUNA GD Page131 | 280


21CS62 Course Title : Fullstack Development

python manage.py runserver

Visit http://127.0.0.1:8000/event/fruits/ and http://127.0.0.1:8000/event/students/ in your


web browser to see the list of fruits and selected students for the event, respectively.

This example demonstrates how to create a simple Django app with two views to display static
lists of fruits and selected students for an event. You can extend this app further by adding
dynamic data and additional functionality as needed.
2.8.2 Develop A Layout.Html With A Suitable Header (Containing A Navigation Menu) And Footer With
Copyright And Developer Information. Inherit This Layout.Html And Create 3 Additional Pages:
Contact Us, About Us, And The Home Page Of Any Website.
let's create a layout template (layout.html) with a header containing a navigation menu and a
footer with copyright and developer information. Then, we'll create three additional pages
(contact_us.html, about_us.html, and home.html) by inheriting from the layout.html template.

1. Create Layout Template:

Create a layout template named layout.html in the templates directory of your Django app.

<!-- templates/layout.html -->

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>{% block title %}My Website{% endblock %}</title>

</head>

<body>

<header>

<h1>My Website</h1>

<nav>

<ul>

<li><a href="{% url 'home' %}">Home</a></li>

<li><a href="{% url 'about_us' %}">About Us</a></li>

<li><a href="{% url 'contact_us' %}">Contact Us</a></li>

</ul>

MALLIKARJUNA GD Page132 | 280


21CS62 Course Title : Fullstack Development

</nav>

</header>

<main>

{% block content %}

{% endblock %}

</main>

<footer>

<p>&copy; 2024 My Website. All rights reserved. Developed by John Doe.</p>

</footer>

</body>

</html>

2. Create Additional Pages:

Create three additional templates (contact_us.html, about_us.html, and home.html) in the


templates directory, inheriting from the layout.html template.

<!-- templates/home.html -->

{% extends 'layout.html' %}

{% block title %}Home - My Website{% endblock %}

{% block content %}

<h2>Welcome to the Home Page</h2>

<p>This is the content of the home page.</p>

{% endblock %}

<!-- templates/about_us.html -->

{% extends 'layout.html' %}

MALLIKARJUNA GD Page133 | 280


21CS62 Course Title : Fullstack Development

{% block title %}About Us - My Website{% endblock %}

{% block content %}

<h2>About Us</h2>

<p>This page provides information about our company.</p>

{% endblock %}

<!-- templates/contact_us.html -->

{% extends 'layout.html' %}

{% block title %}Contact Us - My Website{% endblock %}

{% block content %}

<h2>Contact Us</h2>

<p>Get in touch with us using the contact information below.</p>

{% endblock %}

3. Define URLs:

Define URL patterns for the three additional pages in the urls.py file of your app.

# urls.py

from django.urls import path

from . import views

urlpatterns = [

path('', views.home, name='home'),

path('about_us/', views.about_us, name='about_us'),

path('contact_us/', views.contact_us, name='contact_us'),

4. Define Views (Optional):

Define views for the three additional pages in the views.py file of your app. You can skip this
step if you're only displaying static content.

5. Run the Development Server:

Run the Django development server to see the application in action.

MALLIKARJUNA GD Page134 | 280


21CS62 Course Title : Fullstack Development

python manage.py runserver

Now, you can visit the following URLs in your web browser:

Home Page: http://127.0.0.1:8000/

About Us Page: http://127.0.0.1:8000/about_us/

Contact Us Page: http://127.0.0.1:8000/contact_us/

Each page will inherit the layout defined in layout.html, including the header with the navigation
menu and the footer with copyright and developer information.
2.8.3 Develop A Django App That Performs Student Registration To A Course. It Should Also Display A
List Of Students Registered For Any Selected Course. Create Students And Courses As Models With
Enrolment As Manytomany Field.
let's create a Django app for student registration to a course. We'll define two models: Student
and Course, and establish a ManyToMany relationship between them using an intermediate
model Enrolment. This will allow us to register students for courses and display a list of students
registered for any selected course.
1. Create Django App:
First, create a new Django app within your project.

python manage.py startapp registration

2. Define Models:

Define the Student, Course, and Enrolment models in the registration/models.py file.

# registration/models.py
from django.db import models

class Student(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(unique=True)

def __str__(self):
return self.name

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

def __str__(self):
return self.name

class Enrolment(models.Model):

MALLIKARJUNA GD Page135 | 280


21CS62 Course Title : Fullstack Development

student = models.ForeignKey(Student, on_delete=models.CASCADE)


course = models.ForeignKey(Course, on_delete=models.CASCADE)
date_enrolled = models.DateTimeField(auto_now_add=True)

def __str__(self):
return f"{self.student.name} enrolled in {self.course.name}"

3. Register Models:

Register the Student, Course, and Enrolment models in the registration/admin.py file to make
them accessible in the Django admin interface.

# registration/admin.py
from django.contrib import admin
from .models import Student, Course, Enrolment

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

4. Define Views (Optional):

Define views to handle student registration and course enrollment if needed. For this example,
we'll keep it simple and won't define any views.
5. Run Migrations:

Apply database migrations to create the necessary database tables for the models.

python manage.py makemigrations


python manage.py migrate

6. Test in Django Admin:

Now, you can test the app in the Django admin interface. Run the development server:

python manage.py runserver

Then, navigate to http://127.0.0.1:8000/admin in your browser, log in with your superuser


credentials, and you should be able to add students, courses, and enrollments.
7. Display List of Students for Selected Course:

MALLIKARJUNA GD Page136 | 280


21CS62 Course Title : Fullstack Development

To display a list of students registered for any selected course, you can create a view and
template to handle this functionality. Define appropriate URL patterns, views, and templates as
needed based on your requirements.

This example demonstrates how to create a Django app for student registration to a course,
establish a ManyToMany relationship between students and courses, and display a list of
students registered for any selected course. You can further extend this app with additional
features such as user authentication, form validation, and more sophisticated views

MALLIKARJUNA GD Page137 | 280


21CS62 Course Title : Fullstack Development

2.9 IMPORTANT NOTE


• What is the purpose of Django's template system?
• How does Django's template system help in separating presentation logic from business
logic?
• Explain the syntax of Django templates.
• What are template tags and how are they used in Django templates?
• What are template filters and how are they applied in Django templates?
• How do you integrate Django templates into your Django project?
• Explain the role of the render() function in Django views.
• How can you pass data from views to templates in Django?
• Describe the process of rendering a template in a Django view.
• What are the advantages of using Django's template system compared to raw HTML?
• What are template tags and why are they used in Django templates?
• Provide examples of conditional rendering using template tags.
• How do you loop over data using template tags in Django?
• Explain the purpose of the {% block %} tag in Django templates.
• What are template filters and how do they modify template variables?
• What is template inheritance in Django and why is it useful?
• How do you create a base template in Django?
• Explain the concept of blocks in Django templates.
• How can you extend a base template to create child templates?
• Provide examples of overriding blocks in child templates.

2.9. MCQ
Question 1: What is the purpose of Django's template system?

A) To manage database queries

B) To handle user authentication

C) To separate presentation logic from business logic(correct)

D) To define URL patterns

Explanation: Django's template system is designed to separate the presentation logic (HTML
markup) from the business logic (Python code), promoting code organization and
maintainability.

Question 2: Which function is used to render templates in Django views?

A) render_template()

B) render_to_response()

C) render() (correct)

MALLIKARJUNA GD Page138 | 280


21CS62 Course Title : Fullstack Development

D) render_view()

Explanation: The render() function in Django views is used to render templates by combining
them with a given context.

Question 3: What are template tags used for in Django templates?

A) To define URL patterns

B) To include external CSS files

C) To embed Python code in templates

D) To display dynamic data and control flow logic (correct)

Explanation: Template tags in Django templates are used to embed Python-like code for
displaying dynamic data, performing control flow logic, and more.

Question 4: Which tag is used to define blocks in Django templates for template inheritance?

A) {% content %}

B) {% define %}

C) {% block %} (correct)

D) {% extend %}

Explanation: The {% block %} tag in Django templates is used to define blocks that can be
overridden by child templates in the context of template inheritance.

Question 4: What is the primary advantage of using Django's template system?

A) Better database performance

B) Improved security

C) Enhanced code organization and readability (correct)

D) Simplified user authentication

Explanation: Django's template system helps in organizing code by separating presentation logic
from business logic, making it easier to maintain and understand.

Question 5: Which of the following is an example of a template filter in Django?

A) {% if %}

B) {{ variable|date }} (correct)

MALLIKARJUNA GD Page139 | 280


21CS62 Course Title : Fullstack Development

C) {% for %}

D) {{ variable }}

Explanation: The date filter in Django is applied to a variable to format it as a date according to
a specified format.

Question 6: What does template inheritance allow you to do in Django?

A) Share templates between different Django apps

B) Extend the functionality of Django models

C) Create a base template with common elements and extend it in child templates(correct)

D) Define custom template tags and filters

Explanation: Template inheritance in Django allows you to create a base template with common
elements and then extend it in child templates to override specific blocks or add additional
content.

Question 7: Which function is used to pass data from views to templates in Django?

A) context_data()

B) get_context_data()

C) render_template()

D) render() (correct)

Explanation: The render() function in Django views is used to pass data from views to templates
by combining them with a given context.

Question 8: What happens if a block is not overridden in a child template?

A) The parent template raises an error

B) The content of the block is rendered as defined in the parent template(correct)

C) The child template raises an error

D) The content of the block is ignored

Explanation: If a block is not overridden in a child template, Django renders the content of that
block as defined in the parent template.

Question 9: Can you have multiple levels of template inheritance in Django?

MALLIKARJUNA GD Page140 | 280


21CS62 Course Title : Fullstack Development

A) Yes, Django supports only single-level template inheritance

B) No, Django does not support template inheritance

C) Yes, you can have multiple levels of template inheritance(correct)

D) Yes, but it requires custom template loaders

Explanation: Django supports multiple levels of template inheritance, allowing child templates
to serve as parent templates for other child templates.

MALLIKARJUNA GD Page141 | 280


21CS62 Course Title : Fullstack Development

MODULE-3: DJANGO ADMIN INTERFACES AND MODEL FORMS


DJANGO ADMIN INTERFACE

Django's admin interface is a powerful feature that comes built-in with the Django web
framework. It provides a ready-to-use, customizable, web-based interface for managing the
data in your Django application. The admin interface is automatically generated based on your
Django models, making it easy to perform common CRUD (Create, Read, Update, Delete)
operations on your application's data without having to write custom views or forms.

Key aspects of Django's admin interface:

Automatic CRUD Operations:

• Once you define your models in Django, the admin interface automatically generates an
interface for managing those models.
• You can create, read, update, and delete instances of your models directly from the admin
interface without writing any additional code.

Customization:

• While the admin interface is automatically generated, Django provides extensive


customization options.
• You can customize the appearance and behavior of the admin interface using Python classes
and options.
• Customizations include defining custom admin views, adding filters, creating custom
actions, and more.

Integration with Django's Authentication System:

• Django's admin interface integrates seamlessly with Django's built-in authentication


system.
• This means you can control access to different parts of the admin interface based on user
permissions and groups.
• You can define which users have access to the admin interface and what actions they can
perform.

Internationalization:

• Django's admin interface supports internationalization out of the box.


• You can easily translate the admin interface into multiple languages, making it accessible to
users from different regions.

Development and Debugging:

MALLIKARJUNA GD Page142 | 280


21CS62 Course Title : Fullstack Development

• During development, the admin interface is a valuable tool for quickly inspecting and
managing your application's data.
• It's particularly useful for debugging and verifying that your models and data are set up
correctly.

Overall, Django's admin interface is a time-saving tool that simplifies the process of managing
data in your Django application. It's highly customizable, integrates seamlessly with Django's
authentication system, and provides a convenient way to interact with your application's data
during development and beyond.

3.0 ACTIVATING ADMIN INTERFACES


Activating the admin interface in Django involves a few simple steps:

Ensure Django Admin is Installed:

First, make sure you have Django installed. You can install it via pip if you haven't already:

pip install django

Add 'django.contrib.admin' to INSTALLED_APPS:

In your Django project's settings file (typically settings.py), ensure that 'django.contrib.admin'
is included in the INSTALLED_APPS setting. This is necessary to enable the admin interface.

LED_APPS = [

...

'django.contrib.admin',

...

Run Migrations:

If you haven't already, you need to run the makemigrations and migrate commands to create
and apply the necessary database migrations for the admin interface.

python manage.py makemigrations

python manage.py migrate

Create a Superuser:

To access the admin interface, you need to create a user account with superuser privileges. Run
the following command and follow the prompts to create a superuser account:

MALLIKARJUNA GD Page143 | 280


21CS62 Course Title : Fullstack Development

python manage.py createsuperuser

Accessing the Admin Interface:

Once you've created the superuser account, you can start the Django development server:

python manage.py runserver

Then, you can access the admin interface by navigating to http://127.0.0.1:8000/admin in your
web browser and logging in with the superuser credentials you just created.

Optional: Customize the Admin Interface:

While the default admin interface is functional, you may want to customize it to better suit your
application's needs. You can customize the admin interface by creating admin site classes,
customizing model admin classes, or overriding admin templates.

By following these steps, you should be able to activate and access the admin interface in your
Django project.

3.1 USING ADMIN INTERFACES


The Django admin interface serves several key purposes in web development:

• Rapid Prototyping and Development: During the early stages of development, the admin
interface allows developers to quickly prototype and develop features without building
custom user interfaces. It provides a ready-made interface for managing data models, which
speeds up development time.
• Data Management: The admin interface is a powerful tool for managing data in Django
applications. It allows administrators to perform CRUD (Create, Read, Update, Delete)
operations on database records without writing custom views or forms. This includes
creating, editing, and deleting records, as well as searching and filtering data.
• Content Management: For content-heavy websites such as blogs, news sites, or e-
commerce platforms, the admin interface simplifies content management tasks. Content
editors can use the admin interface to create and update articles, products, or other types
of content without needing technical knowledge or access to the codebase.
• User Management: Django's admin interface integrates with the authentication system,
allowing administrators to manage user accounts, permissions, and groups. This includes
creating new user accounts, assigning permissions, resetting passwords, and managing user
sessions.
• Customization and Extensibility: While the admin interface provides a lot of functionality
out of the box, it's also highly customizable and extensible. Developers can customize the
appearance and behavior of the admin interface by creating custom admin views, defining
custom actions, adding filters, and overriding templates. This allows developers to tailor the
admin interface to fit the specific needs of their applications.

MALLIKARJUNA GD Page144 | 280


21CS62 Course Title : Fullstack Development

• Internal Tools and Dashboards: The admin interface is not limited to managing data models
defined in the Django application. It can also be used to create internal tools and
dashboards for administrative tasks, reporting, or monitoring. Developers can create
custom admin views to display analytics, generate reports, or perform other administrative
tasks.

Overall, the Django admin interface is a versatile tool that simplifies data management, content
management, and user management tasks in Django applications. It provides a user-friendly
interface for administrators and content editors, while also offering flexibility and extensibility
for developers to customize and extend its functionality.

3.2 AUTHENTICATION AND AUTHORIZATION


In Django, authentication and authorization are handled by the django.contrib.auth module,
which provides a robust framework for managing user accounts, permissions, and groups.
Here's an overview of how authentication and authorization work in Django:

Authentication

Authentication is the process of verifying a user's identity. In Django, this is typically handled
through login forms, user models, and authentication backends.

Key Components:

User Model:

The default user model is django.contrib.auth.models.User, which includes fields like username,
password, email, first_name, and last_name.

You can create a custom user model by inheriting from AbstractUser or AbstractBaseUser and
specifying it in the AUTH_USER_MODEL setting.

Authentication Views:

Django provides built-in views for login (LoginView) and logout (LogoutView).

URLs for these views can be included in your urls.py file, typically using the
django.contrib.auth.urls module.

Forms:

AuthenticationForm is the default form for user login.

Custom forms can be created by extending AuthenticationForm or using forms from


django.forms.

Authentication Backends:

MALLIKARJUNA GD Page145 | 280


21CS62 Course Title : Fullstack Development

Django uses authentication backends to check a user's credentials. The default backend is
django.contrib.auth.backends.ModelBackend.

You can add custom backends by implementing the authenticate and get_user methods.

Example Usage:

# urls.py

from django.urls import path

from django.contrib.auth import views as auth_views

urlpatterns = [

path('login/', auth_views.LoginView.as_view(), name='login'),

path('logout/', auth_views.LogoutView.as_view(), name='logout'),

# settings.py

AUTH_USER_MODEL = 'myapp.CustomUser'

Authorization

Authorization is the process of determining what a user is allowed to do. This involves
checking user permissions and group memberships.

Key Components:

Permissions:

Django's default permissions (add, change, delete, and view) are associated with each model.

Custom permissions can be defined in the model's Meta class using the permissions attribute.

Groups:

Groups are a way to categorize users with common permissions.

Users can be added to groups, and permissions can be assigned to groups, which are then
inherited by the users in those groups.

Permission Checking:

Use the has_perm method to check if a user has a specific permission.

The @permission_required decorator can be used to protect views that require specific
permissions.

MALLIKARJUNA GD Page146 | 280


21CS62 Course Title : Fullstack Development

Example Usage:

# models.py

from django.contrib.auth.models import AbstractUser, Group, Permission

from django.db import models

class CustomUser(AbstractUser):

pass

# admin.py

from django.contrib import admin

from django.contrib.auth.admin import UserAdmin

from .models import CustomUser

admin.site.register(CustomUser, UserAdmin)

# views.py

from django.contrib.auth.decorators import login_required, permission_required

from django.shortcuts import render

@login_required

def my_view(request):

return render(request, 'my_template.html')

@permission_required('myapp.special_permission')

def special_view(request):

return render(request, 'special_template.html')

Customizing Authentication and Authorization

Custom User Model:

Create a new user model by extending AbstractUser or AbstractBaseUser.

Update the AUTH_USER_MODEL setting.

Custom Permissions:

MALLIKARJUNA GD Page147 | 280


21CS62 Course Title : Fullstack Development

Define custom permissions in the model's Meta class.

Use the add_perm, remove_perm, and has_perm methods to manage permissions


dynamically.

Custom Authentication Backend:

Implement a custom backend by subclassing BaseBackend and overriding the authenticate


and get_user methods.

# custom_backend.py

from django.contrib.auth.backends import BaseBackend

from django.contrib.auth import get_user_model

class CustomBackend(BaseBackend):

def authenticate(self, request, username=None, password=None, **kwargs):

User = get_user_model()

try:

user = User.objects.get(username=username)

if user.check_password(password):

return user

except User.DoesNotExist:

return None

def get_user(self, user_id):

User = get_user_model()

try:

return User.objects.get(pk=user_id)

except User.DoesNotExist:

return None

MALLIKARJUNA GD Page148 | 280


21CS62 Course Title : Fullstack Development

# settings.py

AUTHENTICATION_BACKENDS = ['myapp.custom_backend.CustomBackend',
'django.contrib.auth.backends.ModelBackend']

By utilizing these components, you can effectively manage authentication and authorization in
your Django applications.

3.3 CUSTOMIZING ADMIN INTERFACES


Customizing the Django admin interface involves various techniques to tailor the appearance
and functionality of the admin pages. Below, I'll outline different types of customizations with
code snippets using the example of Author and Book models.
1. Customizing Admin Templates
Create a Custom Template Directory
Create a directory structure in your project to hold the custom admin templates. For example:
myproject/
myapp/
templates/
admin/
change_form.html
Extend the Default Template

In change_form.html, you can extend the default Django admin template and customize it as
needed.
Here’s a basic example:
{% extends "admin/change_form.html" %}
{% block content %}
<h1>Custom Change Form</h1>
<p>This is a custom change form template.</p>
{{ block.super }}
{% endblock %}
Configure Django to Use Custom Templates
Make sure Django knows where to find your custom templates. In your project's settings file
(settings.py), set the DIRS option in the TEMPLATES setting to include the path to your custom
templates:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',

MALLIKARJUNA GD Page149 | 280


21CS62 Course Title : Fullstack Development

'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Add Your Custom Logic
You can add any custom logic, forms, or additional blocks to the template as needed. For
example, to add a custom form field, you might modify the template like this:
{% extends "admin/change_form.html" %}
{% block content %}
<h1>Custom Change Form</h1>
<form method="post" enctype="multipart/form-data" class="custom-form">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save changes</button>
</form>
{{ block.super }}
{% endblock %}
Apply Custom CSS/JS
If you need to add custom CSS or JavaScript, you can include them in the template as well:
{% extends "admin/change_form.html" %}
{% block extrahead %}
{{ block.super }}
<link rel="stylesheet" type="text/css" href="{% static 'css/custom_admin.css' %}">
<script src="{% static 'js/custom_admin.js' %}"></script>
{% endblock %}
{% block content %}
<h1>Custom Change Form</h1>
<form method="post" enctype="multipart/form-data" class="custom-form">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save changes</button>
</form>
{{ block.super }}
{% endblock %}
Example Custom Template Structure
Here's an example of how your template directory might look:
myproject/
myapp/
templates/

MALLIKARJUNA GD Page150 | 280


21CS62 Course Title : Fullstack Development

admin/
change_form.html
static/
css/
custom_admin.css
js/
custom_admin.js
This setup ensures that you can extend and customize the Django admin interface according to
your requirements.
2. Customizing ModelAdmin Classes
Example: Customize List Display and Filters
Customize the display and filters for the AuthorAdmin and BookAdmin classes.
from django.contrib import admin
from .models import Author, Book

class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'published_date', 'isbn')
list_filter = ('author', 'published_date')
search_fields = ('title', 'author__name')
ordering = ('-published_date',)
date_hierarchy = 'published_date'

admin.site.register(Book, BookAdmin)

class AuthorAdmin(admin.ModelAdmin):
list_display = ('name', 'birthdate')
search_fields = ('name',)

admin.site.register(Author, AuthorAdmin)

3. Customizing Inline Forms


Example: Customize Inline Editing for Books
Define a custom form and inline admin class for editing Book instances inline within Author
admin.

from django import forms


from django.contrib import admin
from .models import Author, Book

class BookInlineForm(forms.ModelForm):
class Meta:
model = Book

MALLIKARJUNA GD Page151 | 280


21CS62 Course Title : Fullstack Development

fields = ('title', 'published_date', 'isbn')

def clean_isbn(self):
isbn = self.cleaned_data.get('isbn')
# Add custom validation logic if needed
return isbn

class BookInline(admin.TabularInline):
model = Book
form = BookInlineForm
extra = 5
fields = ('title', 'published_date', 'isbn')
readonly_fields = ('published_date',)
can_delete = True

class AuthorAdmin(admin.ModelAdmin):
list_display = ('name', 'birthdate')
search_fields = ('name',)
inlines = [BookInline]

admin.site.register(Author, AuthorAdmin)

4. Customizing Fieldsets
Example: Define Fieldsets for AuthorAdmin
Organize fields into sections (fieldsets) within the Author admin.
class AuthorAdmin(admin.ModelAdmin):
list_display = ('name', 'birthdate')
search_fields = ('name',)
fieldsets = (
(None, {
'fields': ('name', 'birthdate')
}),
('Advanced options', {
'classes': ('collapse',),
'fields': ('extra_info',)
}),
)

admin.site.register(Author, AuthorAdmin)

5. Adding Custom Actions

MALLIKARJUNA GD Page152 | 280


21CS62 Course Title : Fullstack Development

Example: Define a Custom Action for BookAdmin


Add a custom action to perform bulk operations on selected books.

def mark_as_published(modeladmin, request, queryset):


queryset.update(status='published')

mark_as_published.short_description = "Mark selected books as published"

class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'published_date', 'isbn')
list_filter = ('author', 'published_date')
search_fields = ('title', 'author__name')
ordering = ('-published_date',)
date_hierarchy = 'published_date'
actions = [mark_as_published]

admin.site.register(Book, BookAdmin)

6. Adding Custom Validation


Example: Validate ISBN Field in Book Model
Define a custom clean method in the Book model admin to validate ISBNs.
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'published_date', 'isbn')
list_filter = ('author', 'published_date')
search_fields = ('title', 'author__name')
ordering = ('-published_date',)
date_hierarchy = 'published_date'

def clean_isbn(self, request, queryset):


isbn = self.cleaned_data.get('isbn')
# Custom validation logic
if not isbn.startswith('978'):
raise forms.ValidationError("ISBN must start with 978")
return isbn

admin.site.register(Book, BookAdmin)

Oveall,
• Admin Templates: Modify HTML templates to change the admin interface layout.
• ModelAdmin Classes: Customize how models are displayed and interacted with in the
admin.
• Inline Forms: Edit related models inline within parent model forms.

MALLIKARJUNA GD Page153 | 280


21CS62 Course Title : Fullstack Development

• Fieldsets: Organize fields into sections within the admin interface.


• Custom Actions: Add custom actions to perform batch operations on selected objects.
• Custom Validation: Implement custom validation logic for model fields.

3.4 FORM PROCESSING


In Django, forms are an essential part of web development. They provide a way to handle user
input, validate data, and render form elements in templates. Django forms offer built-in
methods and functionalities to simplify the process of dealing with forms, including validation
and error handling.

Types of Django Forms:

Django provides different types of forms to handle various use cases.

• Django Forms (forms.Form): For handling simple, non-model-based data.

• Django Model Forms (forms.ModelForm): Tied to Django models for creating and updating
instances.

• Formsets: For managing multiple forms on a single page.

• Model Formsets: For managing multiple model instances.

• Inline Formsets: For managing related objects in parent-child relationships.

1. Django Forms (forms.Form):

Django forms (forms.Form) are a powerful tool for handling and validating user input in web
applications. They provide an easy way to render HTML forms, manage user input, and validate
data. Below is a comprehensive overview of Django forms, including how to create and use
them.

Creating a Form Class

A form class is created by inheriting from forms.Form. You define fields as class attributes.

Example:

from django import forms

class ContactForm(forms.Form):

name = forms.CharField(max_length=100)

email = forms.EmailField()

message = forms.CharField(widget=forms.Textarea)

In this example:

MALLIKARJUNA GD Page154 | 280


21CS62 Course Title : Fullstack Development

name is a CharField with a maximum length of 100 characters.

email is an EmailField that ensures the input is a valid email address.

message is a CharField that uses a Textarea widget for multiline input.

2. Rendering the Form in a Template

To display the form in an HTML template, you create an instance of the form and pass it to the
template context.

View:

from django.shortcuts import render

from .forms import ContactForm

def contact_view(request):

form = ContactForm()

return render(request, 'contact.html', {'form': form})

Template (contact.html):

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Contact Form</title>

</head>

<body>

<h1>Contact Us</h1>

<form method="post">

{% csrf_token %}

{{ form.as_p }}

<button type="submit">Send</button>

</form>

</body>

MALLIKARJUNA GD Page155 | 280


21CS62 Course Title : Fullstack Development

</html>

{% csrf_token %} is a template tag that ensures the form is protected against Cross-Site Request
Forgery (CSRF) attacks.

{{ form.as_p }} renders the form fields as <p> elements. Other rendering options include
form.as_table and form.as_ul.

3. Handling Form Submission and Validation

When the form is submitted, you handle the POST request, validate the form data, and process
the valid data.

View:

from django.shortcuts import render

from django.http import HttpResponse

from .forms import ContactForm

def contact_view(request):

if request.method == 'POST':

form = ContactForm(request.POST)

if form.is_valid():

# Process the data in form.cleaned_data

name = form.cleaned_data['name']

email = form.cleaned_data['email']

message = form.cleaned_data['message']

# For example, send an email or save to database

return HttpResponse('Thank you for your message.')

else:

form = ContactForm()

return render(request, 'contact.html', {'form': form})

form.cleaned_data is a dictionary containing the validated form data.

If the form is not valid, the form instance will contain error messages, which can be displayed
in the template.

MALLIKARJUNA GD Page156 | 280


21CS62 Course Title : Fullstack Development

4. Form Validation

Django forms provide built-in validation for common fields, and you can also add custom
validation.

Custom validation example:

class ContactForm(forms.Form):

name = forms.CharField(max_length=100)

email = forms.EmailField()

message = forms.CharField(widget=forms.Textarea)

def clean_email(self):

email = self.cleaned_data.get('email')

if not email.endswith('@example.com'):

raise forms.ValidationError('Please use an @example.com email address.')

return email

clean_<fieldname> methods are used to add custom validation for individual fields.

raise forms.ValidationError is used to raise validation errors.

5. Widgets and Customizing Form Fields

Widgets define how form fields are rendered. You can customize them or use built-in widgets.

Example:

class ContactForm(forms.Form):

name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-


control'}))

email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'}))

message = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 5}))

The attrs parameter allows you to add HTML attributes to the rendered form fields.

6. Error Handling and Displaying Errors

Django automatically handles form errors and displays them in the template.

Template example:

MALLIKARJUNA GD Page157 | 280


21CS62 Course Title : Fullstack Development

<form method="post">

{% csrf_token %}

{{ form.non_field_errors }}

{{ form.as_p }}

<button type="submit">Send</button>

</form>

form.non_field_errors displays errors that are not associated with a specific field.

7. Advanced Features

Initial Values: You can set initial values for form fields.

form = ContactForm(initial={'name': 'John Doe'})

Field Order: You can change the order of form fields using the Meta class.

class ContactForm(forms.Form):

name = forms.CharField(max_length=100)

email = forms.EmailField()

message = forms.CharField(widget=forms.Textarea)

class Meta:

field_order = ['email', 'name', 'message']

Dynamic Forms: You can dynamically add or remove fields based on certain conditions.

class ContactForm(forms.Form):

name = forms.CharField(max_length=100)

email = forms.EmailField(required=False)

def __init__(self, *args, **kwargs):

super().__init__(*args, **kwargs)

if some_condition:

self.fields['email'].required = True

MALLIKARJUNA GD Page158 | 280


21CS62 Course Title : Fullstack Development

Django forms (forms.Form) are a flexible and powerful way to handle user input, validate data,
and render HTML forms. They are designed to make it easy to create, process, and validate
forms in your Django web applications. With built-in support for common form fields and
validation, as well as the ability to customize and extend functionality, Django forms are an
essential part of any Django developer’s toolkit.

2. MODEL FORM:

Model forms in Django are a powerful tool for handling HTML forms in web applications. They
simplify the process of creating forms for data input and validation, particularly when working
with Django models.

An explanation of model forms in Django:

Automatic Form Generation:

• Django's model forms automatically generate HTML form elements based on the fields of a
Django model.
• When you define a model form class, Django inspects the model's fields and generates form
fields accordingly.
• This saves you from manually defining each form field, as Django does it for you based on
the model's structure.

Validation:

• Model forms provide built-in validation based on the model's field definitions.
• When a form is submitted, Django validates the input data according to the model's field
types, constraints, and custom validation logic.
• If the data is invalid, Django returns errors that can be displayed to the user to correct their
input.

Data Binding:

• After a form is submitted and passes validation, Django automatically binds the submitted
data to the corresponding model instance.
• This means you can easily create, update, or delete database records based on the form's
data without writing additional code to map form fields to model fields.

Customization:

• While model forms automatically generate form fields based on the model's fields, you can
still customize the form's appearance and behavior.
• You can override default field widgets, add additional fields not present in the model, or
exclude certain fields from the form.
• Customization allows you to tailor the form to suit your application's specific requirements.

MALLIKARJUNA GD Page159 | 280


21CS62 Course Title : Fullstack Development

Integration with Views:

• Model forms are typically used in Django views to handle form processing.
• In a view function or class-based view, you instantiate a model form, pass it to the template
context, and render it in the HTML template.
• When the form is submitted, the view receives the form data, validates it, and performs the
necessary actions based on the form's validity.

The overall model forms in Django streamline the process of working with HTML forms by
automatically generating form elements based on Django models. They handle validation, data
binding, and provide customization options, making them a convenient and efficient tool for
building web forms in Django applications.

let's create a complete Django application from scratch using forms.ModelForm to handle a
simple contact form. This example will cover setting up the project, defining the model, creating
the form, setting up views and templates, and configuring URLs.

Step-by-Step Implementation

1. Set Up the Django Project and App

1. First, create a Django project and an app.

django-admin startproject mysite

cd mysite

python manage.py startapp contact

2. Define the Contact Model

Create a model to represent the contact form data in contact/models.py.

# contact/models.py

from django.db import models

class Contact(models.Model):

name = models.CharField(max_length=100)

email = models.EmailField()

message = models.TextField()

def __str__(self):

return self.name

MALLIKARJUNA GD Page160 | 280


21CS62 Course Title : Fullstack Development

3. Create the Contact Form

Create a form class using forms.ModelForm in contact/forms.py.

# contact/forms.py

from django import forms

from .models import Contact

class ContactForm(forms.ModelForm):

class Meta:

model = Contact

fields = ['name', 'email', 'message']

4. Create Views to Handle the Form

Define views to render the form and handle form submission in contact/views.py.

# contact/views.py

from django.shortcuts import render, redirect

from django.http import HttpResponse

from .forms import ContactForm

def contact_view(request):

if request.method == 'POST':

form = ContactForm(request.POST)

if form.is_valid():

form.save() # Automatically saves to the database

return HttpResponse('Thank you for your message.')

else:

form = ContactForm()

return render(request, 'contact/contact.html', {'form': form})

5. Configure URLs

Add a URL pattern for the contact view in contact/urls.py.

MALLIKARJUNA GD Page161 | 280


21CS62 Course Title : Fullstack Development

# contact/urls.py

from django.urls import path

from .views import contact_view

urlpatterns = [

path('', contact_view, name='contact'),

Include the app’s URL configuration in the project’s urls.py.

# mysite/urls.py

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path('admin/', admin.site.urls),

path('contact/', include('contact.urls')),

6. Create Templates

Create a template for the contact form in contact/templates/contact/contact.html.

<!-- contact/templates/contact/contact.html -->

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Contact Form</title>

</head>

<body>

<h1>Contact Us</h1>

<form method="post">

{% csrf_token %}

MALLIKARJUNA GD Page162 | 280


21CS62 Course Title : Fullstack Development

{{ form.as_p }}

<button type="submit">Send</button>

</form>

</body>

</html>

7. Run Migrations and Start the Server

Run the initial migrations to create the database tables and start the development server.

python manage.py makemigrations

python manage.py migrate

python manage.py runserver

8. Access the Contact Form

Open your web browser and navigate to http://127.0.0.1:8000/contact/ to see your contact
form in action.

Explanation

Models:

The Contact model defines the structure of the contact form data with fields for name, email,
and message.

Forms:

The ContactForm class inherits from forms.ModelForm.

The Meta class inside ContactForm specifies the model to use (Contact) and the fields to include
in the form (name, email, message).

Views:

The contact_view handles both GET and POST requests.

If the request method is POST, the form is populated with the submitted data and validated.

If the form is valid, it is saved to the database using form.save().

If the form is not valid or it is a GET request, the form is rendered for the user to fill out.

Templates:

MALLIKARJUNA GD Page163 | 280


21CS62 Course Title : Fullstack Development

The template renders the form using {{ form.as_p }} to display each form field wrapped in a <p>
tag.

{% csrf_token %} ensures the form is protected against CSRF attacks.

URLs:

The contact_view is mapped to the root URL of the contact app.

The app’s URL configuration is included in the project’s main URL configuration.

Running the Server:

Migrations are run to set up the database tables for the Contact model.

The development server is started using runserver.

Inotherwords, This example demonstrates how to use forms.ModelForm in Django to create a


simple contact form that interacts with the database. By following these steps, you can easily
create forms tied to your models, handle form submissions, validate user input, and save the
data to the database.

Formsets: For managing multiple forms on a single page

Formsets allow you to manage multiple instances of a single form on a single page. This is
particularly useful when you need to handle multiple objects of the same type in a single view,
such as creating or updating multiple projects at once.

Example: Using Formsets to Manage Multiple Projects

Step 1: Define the Model

If you haven't already, define your model in projects/models.py.

from django.db import models

class Project(models.Model):

student_name = models.CharField(max_length=100)

topic = models.CharField(max_length=200)

languages = models.CharField(max_length=200)

duration = models.IntegerField(help_text="Duration in hours")

def __str__(self):

MALLIKARJUNA GD Page164 | 280


21CS62 Course Title : Fullstack Development

return f"{self.student_name} - {self.topic}"

Step 2: Create a Form for the Model

In projects/forms.py, create a form for the Project model.

from django import forms

from .models import Project

class ProjectForm(forms.ModelForm):

class Meta:

model = Project

fields = ['student_name', 'topic', 'languages', 'duration']

Step 3: Create a Formset for the Form

Still in projects/forms.py, create a formset for the ProjectForm.

from django.forms import modelformset_factory

ProjectFormSet = modelformset_factory(Project, form=ProjectForm, extra=3)

Step 4: Create Views to Handle the Formset

In projects/views.py, create views to handle the formset.

from django.shortcuts import render, redirect

from .forms import ProjectFormSet

def project_create_view(request):

if request.method == 'POST':

formset = ProjectFormSet(request.POST)

if formset.is_valid():

formset.save()

return redirect('project_success')

else:

formset = ProjectFormSet()

return render(request, 'projects/project_formset.html', {'formset': formset})

MALLIKARJUNA GD Page165 | 280


21CS62 Course Title : Fullstack Development

def project_success_view(request):

return render(request, 'projects/project_success.html')

Step 5: Create URL Patterns

In projects/urls.py, add URL patterns for the new views.

from django.urls import path

from .views import project_create_view, project_success_view

urlpatterns = [

path('create/', project_create_view, name='project_create'),

path('success/', project_success_view, name='project_success'),

Step 6: Create Templates for the Formset

Create a new file project_formset.html in the projects/templates/projects/ directory.

<!DOCTYPE html>

<html>

<head>

<title>Create Projects</title>

</head>

<body>

<h2>Create Projects</h2>

<form method="post">

{% csrf_token %}

{{ formset.management_form }}

{% for form in formset %}

MALLIKARJUNA GD Page166 | 280


21CS62 Course Title : Fullstack Development

{{ form.as_p }}

{% endfor %}

<button type="submit">Save</button>

</form>

</body>

</html>

And modify the project_success.html template if necessary.

<!DOCTYPE html>

<html>

<head>

<title>Projects Created</title>

</head>

<body>

<h2>Projects created successfully!</h2>

<a href="{% url 'project_create' %}">Create more projects</a>

</body>

</html>

Step 7: Update the Main URLs Configuration

Ensure that the main URL configuration includes the URLs from the projects app.

Open StudentProjectsManager/urls.py and make sure it looks like this:

from django.contrib import admin

from django.urls import include, path

urlpatterns = [

MALLIKARJUNA GD Page167 | 280


21CS62 Course Title : Fullstack Development

path('admin/', admin.site.urls),

path('projects/', include('projects.urls')),

Step 8: Run the Server and Test

Start the Django development server if it's not already running:

python manage.py runserver

Navigate to http://127.0.0.1:8000/projects/create/ to view the formset and create multiple


projects at once.

3.4.1 CREATING FEEDBACK FORMS


Creating a feedback form in Django involves defining a form to collect feedback from users,
creating a view to handle form submissions, and rendering a template to display the form to
users. Let's walk through the steps:

Step 1: Define a Form

First, define a form class in your Django app's forms.py file. This form will include fields to collect
feedback from users. For example:

# myapp/forms.py

from django import forms

class FeedbackForm(forms.Form):

name = forms.CharField(max_length=100)

email = forms.EmailField()

message = forms.CharField(widget=forms.Textarea)

Step 2: Create a View

Next, create a view function or class-based view to handle form processing logic. In this view,
you'll handle form submission, validate the data, and perform actions based on the submitted
data. For example:

# myapp/views.py

from django.shortcuts import render

from .forms import FeedbackForm

MALLIKARJUNA GD Page168 | 280


21CS62 Course Title : Fullstack Development

def feedback_view(request):

if request.method == 'POST':

form = FeedbackForm(request.POST)

if form.is_valid():

# Process the form data (e.g., save to database)

name = form.cleaned_data['name']

email = form.cleaned_data['email']

message = form.cleaned_data['message']

# Redirect to a success page or render a template

else:

form = FeedbackForm()

return render(request, 'feedback_form.html', {'form': form})

Step 3: Create a Template

Create an HTML template to render the feedback form. Include the form fields in the template
using Django template language. For example:

<!-- myapp/templates/feedback_form.html -->

<form method="post">

{% csrf_token %}

{{ form.as_p }}

<button type="submit">Submit Feedback</button>

</form>

Step 4: Configure URLs

Map the view to a URL pattern in your Django project's urls.py file:

# myproject/urls.py

from django.urls import path

from myapp import views

urlpatterns = [

MALLIKARJUNA GD Page169 | 280


21CS62 Course Title : Fullstack Development

path('feedback/', views.feedback_view, name='feedback'),

Step 5: Handling Form Submission

When a user submits the feedback form, Django processes the form data in the view. If the form
is submitted via POST method, Django initializes the form with the submitted data
(request.POST), validates it, and makes the cleaned data available as form.cleaned_data. You
can then perform actions based on this data, such as saving it to a database.

Step 6: Displaying Validation Errors

If the form data is invalid, Django automatically renders the form with validation errors. You can
access these errors in the template using form.errors or display them alongside form fields using
form.field.errors.

Step 7: Adding CSRF Token

Always include a CSRF token in your forms to protect against CSRF attacks. Use the {% csrf_token
%} template tag to include the CSRF token in your form.

Step 8: Redirecting or Rendering Response

After processing the form data, you can redirect the user to a success page or render a template.
Alternatively, you can render the same template with the form to allow users to correct any
validation errors.

You've now created a feedback form in Django, allowing users to submit feedback through a
form, validating it, and performing actions based on the submitted data.

3.4.2 FORM SUBMISSIONS


Form submissions in Django involve handling data sent from HTML forms, processing it in views,
and performing actions based on the submitted data. Here's a step-by-step guide on how to
handle form submissions in Django:

Step 1: Create a Form

Define a form class in your Django app's forms.py file. This form class should inherit from
django.forms.Form or one of its subclasses like django.forms.ModelForm. Here's an example of
a simple form:

# myapp/forms.py

from django import forms

class MyForm(forms.Form):

name = forms.CharField(max_length=100)

MALLIKARJUNA GD Page170 | 280


21CS62 Course Title : Fullstack Development

email = forms.EmailField()

Step 2: Create a View

Define a view function or class-based view to handle form submissions. In the view, you'll handle
form submission, validate the data, and perform actions based on the submitted data. Here's
an example of a view function:

# myapp/views.py

from django.shortcuts import render

from .forms import MyForm

def my_form_view(request):

if request.method == 'POST':

form = MyForm(request.POST)

if form.is_valid():

name = form.cleaned_data['name']

email = form.cleaned_data['email']

# Process the form data (e.g., save to database)

# Redirect to a success page or render a template

else:

form = MyForm()

return render(request, 'my_template.html', {'form': form})

Step 3: Create a Template

Create an HTML template to render the form. Include the form fields in the template using
Django template language. Here's an example of a template (my_template.html):

<!-- myapp/templates/my_template.html -->

<form method="post">

{% csrf_token %}

{{ form.as_p }}

<button type="submit">Submit</button>

</form>

MALLIKARJUNA GD Page171 | 280


21CS62 Course Title : Fullstack Development

Step 4: Configure URLs

Map the view to a URL pattern in your Django project's urls.py file:

# myproject/urls.py

from django.urls import path

from myapp import views

urlpatterns = [

path('my-form/', views.my_form_view, name='my-form'),

Step 5: Handling Form Submission

When a user submits the form, Django processes the form data in the view. If the form is
submitted via POST method, Django initializes the form with the submitted data (request.POST),
validates it, and makes the cleaned data available as form.cleaned_data. You can then perform
actions based on this data, such as saving it to a database.

Step 6: Displaying Validation Errors

If the form data is invalid, Django automatically renders the form with validation errors. You can
access these errors in the template using form.errors or display them alongside form fields using
form.field.errors.

Step 7: Adding CSRF Token

Always include a CSRF token in your forms to protect against CSRF attacks. Use the {% csrf_token
%} template tag to include the CSRF token in your form.

Step 8: Redirecting or Rendering Response

After processing the form data, you can redirect the user to a success page or render a template.
Alternatively, you can render the same template with the form to allow users to correct any
validation errors.

You've now implemented form submissions in Django, allowing users to submit data through a
form, validating it, and performing actions based on the submitted data

3.4.3 CUSTOM VALIDATION


Custom validation in Django allows you to define custom logic to validate form fields beyond
the default field validation provided by Django's form classes. You can create custom validation
methods within your form class to enforce specific validation rules.

Here's how you can implement custom validation in Django:

MALLIKARJUNA GD Page172 | 280


21CS62 Course Title : Fullstack Development

Step 1: Define a Form

Define your form class in your Django app's forms.py file. Include the fields you want to validate,
and optionally, define custom validation methods. For example:

# myapp/forms.py

from django import forms

class MyForm(forms.Form):

name = forms.CharField(max_length=100)

email = forms.EmailField()

def clean_name(self):

name = self.cleaned_data['name']

if not name.isalpha():

raise forms.ValidationError("Name must only contain alphabetic characters.")

return name

Step 2: Implement Custom Validation Methods

Inside your form class, define custom validation methods prefixed with clean_. These methods
will be automatically called during form validation. In the example above, clean_name() is a
custom validation method that checks if the name contains only alphabetic characters.

Step 3: Handle Validation Errors

If the custom validation fails, raise a forms.ValidationError with an appropriate error message.
Django will collect these errors and display them alongside the corresponding form fields in the
template when rendering the form.

Step 4: Submit and Process the Form

Process the form submission in your view as usual. Django will automatically call the custom
validation methods during form validation. If the form data passes all validation rules, it will be
available in form.cleaned_data.

Example View:

# myapp/views.py

from django.shortcuts import render

MALLIKARJUNA GD Page173 | 280


21CS62 Course Title : Fullstack Development

from .forms import MyForm

def my_form_view(request):

if request.method == 'POST':

form = MyForm(request.POST)

if form.is_valid():

# Process the form data

name = form.cleaned_data['name']

email = form.cleaned_data['email']

# Redirect to a success page or render a template

else:

form = MyForm()

return render(request, 'my_template.html', {'form': form})

Example Template:

<!-- myapp/templates/my_template.html -->

<form method="post">

{% csrf_token %}

{{ form.as_p }}

<button type="submit">Submit</button>

</form>

Custom validation methods in Django forms are automatically called during form validation.

Use clean_<fieldname>() methods to define custom validation logic for specific fields.

If validation fails, raise forms.ValidationError with an appropriate error message.

Django automatically displays validation errors next to corresponding form fields in the
template.

By implementing custom validation in Django forms, you can enforce complex validation rules
tailored to your application's requirements.

MALLIKARJUNA GD Page174 | 280


21CS62 Course Title : Fullstack Development

3.4.4 CREATING MODEL FORMS


Creating model forms in Django allows you to easily create HTML forms based on your Django
model definitions. These forms handle data validation, saving, and updating of model instances.
Here's a step-by-step guide on how to create model forms:

Step 1: Define a Model

First, define your model in your Django app's models.py file. This model will serve as the basis
for your model form. For example:

# myapp/models.py

from django.db import models

class MyModel(models.Model):

name = models.CharField(max_length=100)

email = models.EmailField()

message = models.TextField()

Step 2: Create a ModelForm

Create a model form class in your Django app's forms.py file. This form class should inherit from
django.forms.ModelForm and specify the model it's based on. For example:

# myapp/forms.py

from django import forms

from .models import MyModel

class MyModelForm(forms.ModelForm):

class Meta:

model = MyModel

fields = ['name', 'email', 'message']

Step 3: Display the Form in a Template

Create an HTML template to render the model form. Include the form fields in the template
using Django template language. For example:

<!-- myapp/templates/my_template.html -->

<form method="post">

{% csrf_token %}

MALLIKARJUNA GD Page175 | 280


21CS62 Course Title : Fullstack Development

{{ form.as_p }}

<button type="submit">Submit</button>

</form>

Step 4: Configure URLs

Map a view to a URL pattern in your Django project's urls.py file. This view will handle rendering
the form and processing form submissions. For example:

# myproject/urls.py

from django.urls import path

from myapp import views

urlpatterns = [

path('my-form/', views.my_form_view, name='my-form'),

Step 5: Create a View

Define a view function or class-based view to render the model form and process form
submissions. For example:

# myapp/views.py

from django.shortcuts import render, redirect

from .forms import MyModelForm

def my_form_view(request):

if request.method == 'POST':

form = MyModelForm(request.POST)

if form.is_valid():

form.save()

return redirect('success-url') # Redirect to a success page

else:

form = MyModelForm()

MALLIKARJUNA GD Page176 | 280


21CS62 Course Title : Fullstack Development

return render(request, 'my_template.html', {'form': form})

Model Definition: Define your model in models.py as usual.

ModelForm Definition: Create a model form class in forms.py that inherits from
django.forms.ModelForm and specifies the model it's based on.

Template: Create an HTML template to render the form using Django template language ({{
form.as_p }}).

URL Configuration: Map a view to a URL pattern in urls.py.

View Function: Define a view function or class-based view to render the form and process form
submissions. In the view, create an instance of the model form, handle form validation, and
save the form data if it's valid.

By following these steps, you can easily create model forms in Django and use them to interact
with your database models through HTML forms.

3.4.5 URLCONF TICKS


It seems like you're referring to URLconf, which stands for URL configuration in Django. In
Django, URLconf is a set of patterns used by the URL dispatcher to determine the view that
should handle an incoming HTTP request. Let me provide some key points and "ticks" (steps
or tips) related to URLconf:

1. Define URL Patterns:

Define URL patterns in your Django project's urls.py module. Each URL pattern is a Python
regular expression (regex) pattern mapped to a view function or class-based view.

Use the path() function to define URL patterns in Django 2.0 and later versions. In earlier
versions, you can use url() instead.

2. Include Other URLconfs:

Use the include() function to include other URLconfs from your app modules or external apps.
This allows you to organize your URL configuration into smaller, reusable components.

Include URL patterns from other apps by specifying the app name and URLconf module name.

3. Name Your URL Patterns:

Assign a name to each URL pattern using the name argument. Naming URL patterns makes it
easier to refer to them in templates and view functions using the {% url %} template tag or the
reverse() function.

4. Use Regular Expressions:

MALLIKARJUNA GD Page177 | 280


21CS62 Course Title : Fullstack Development

URL patterns in Django can use regular expressions to match dynamic parts of URLs. Use
capturing groups (()) in your regex patterns to capture parts of the URL and pass them as
arguments to the view function.

5. Order Matters:

The order of URL patterns in your URLconf matters. Django processes URL patterns in the order
they appear in the URLconf, and stops at the first match. Place more specific patterns before
more general ones.

6. Debugging:

Use Django's runserver command with the --traceback option to display detailed error
tracebacks, including information about URL pattern matching and view function execution.

7. Namespacing URL Patterns:

When including URLconfs from other apps, you can namespace the URL patterns to avoid
naming conflicts. Specify the namespace argument when using the include() function, and use
the {% url %} tag with the namespace to refer to specific URL patterns.

8. Grouping URL Patterns:

You can group related URL patterns using the path() function with an empty string as the first
argument. This allows you to apply common prefix or middleware to a group of URL patterns.

By following these ticks, you can effectively configure URL patterns in Django and ensure that
incoming HTTP requests are routed to the appropriate view functions or class-based view

3.4.6 INCLUDING OTHER URLCONFS


Including other URLconfs in Django allows you to organize your URL configuration into smaller,
reusable components. You can include URL patterns from other Django apps or modules into
your project's main URLconf. Here's how to do it:

Step 1: Define URL Patterns in App-level URLconfs

In each Django app that you want to include in your project's main URLconf, define a URLconf
module (urls.py) with its own URL patterns.

For example, in your app's urls.py:

# myapp/urls.py

from django.urls import path

from . import views

urlpatterns = [

path('some-url/', views.some_view, name='some-url'),

MALLIKARJUNA GD Page178 | 280


21CS62 Course Title : Fullstack Development

# Other URL patterns for this app...


]

Step 2: Include App-level URLconfs in Project-level URLconf

In your project's main URLconf (usually located at the root of your project directory), use the
include() function to include URL patterns from each app's URLconf.

For example, in your project's urls.py:

# myproject/urls.py

from django.urls import path, include

urlpatterns = [

path('myapp/', include('myapp.urls')), # Include URLs from the 'myapp' app


# Other URL patterns for your project...
]

Step 3: Access App URLs

Now, all the URL patterns defined in the myapp.urls module will be accessible under the
specified prefix ('myapp/' in this case). For example, if you have a view named some_view in
the myapp app, it will be accessible at /myapp/some-url/.

Tips:

• The include() function allows you to include URL patterns from other modules. You
provide the module path as an argument.
• You can include multiple URLconfs in your project's main URLconf by calling include()
multiple times with different module paths.
• URL patterns in included URLconfs retain their relative paths. This means that if you
include an app's URLconf under a specific prefix, all the URL patterns within that
URLconf will be relative to that prefix.
• URL namespaces can be used to avoid naming conflicts when including multiple
URLconfs with similar URL patterns.
• By including other URLconfs in your project, you can modularize your URL configuration
and make it easier to manage and maintain, especially in larger projects with multiple
apps

3.3. PRACTICE

MALLIKARJUNA GD Page179 | 280


21CS62 Course Title : Fullstack Development

3.3.1 For student and course models created in the Lab experiment for Module 2,
register admin interfaces, perform migrations, and illustrate data entry through admin
forms.
Let's go through the detailed steps from scratch to register the Student and Course models in
the

1. Create a New Django Project

Open a terminal or command prompt and follow these commands to create a new Django
project named myproject:

# Create a new Django project

django-admin startproject myproject

cd myproject

2. Create a New Django App

Inside your Django project, create a new app named myapp:

python manage.py startapp myapp

3. Define Models

Edit myapp/models.py to define your models (Student and Course):

# myapp/models.py

from django.db import models

class Student(models.Model):

first_name = models.CharField(max_length=100)

last_name = models.CharField(max_length=100)

date_of_birth = models.DateField()

email = models.EmailField(unique=True)

def __str__(self):

return f"{self.first_name} {self.last_name}"

class Course(models.Model):

MALLIKARJUNA GD Page180 | 280


21CS62 Course Title : Fullstack Development

name = models.CharField(max_length=200)

code = models.CharField(max_length=10, unique=True)

description = models.TextField()

def __str__(self):

return self.name

4. Register Models with Admin Interface

Create myapp/admin.py to register your models with the admin interface:

# myapp/admin.py

from django.contrib import admin

from .models import Student, Course

@admin.register(Student)

class StudentAdmin(admin.ModelAdmin):

list_display = ('first_name', 'last_name', 'date_of_birth', 'email')

search_fields = ('first_name', 'last_name', 'email')

list_filter = ('date_of_birth',)

@admin.register(Course)

class CourseAdmin(admin.ModelAdmin):

list_display = ('name', 'code')

search_fields = ('name', 'code')

5. Perform Migrations

Apply migrations to create database tables for your models:

MALLIKARJUNA GD Page181 | 280


21CS62 Course Title : Fullstack Development

python manage.py makemigrations

python manage.py migrate

1. create view

# myapp/views.py
from django.shortcuts import render, get_object_or_404
from .models import Student, Course

def student_detail(request, student_id):


student = get_object_or_404(Student, pk=student_id)
return render(request, 'myapp/student_detail.html', {'student':
student})

def course_detail(request, course_id):


course = get_object_or_404(Course, pk=course_id)
return render(request, 'myapp/course_detail.html', {'course':
course})
2. setting.py

# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp'
]

import os
APP_DIR = os.path.join(BASE_DIR, 'myapp')

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(APP_DIR, 'templates')],
'APP_DIRS': True,

MALLIKARJUNA GD Page182 | 280


21CS62 Course Title : Fullstack Development

'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
3. create Template files
student_detail.html
<!-- myapp/templates/myapp/student_detail.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Student Detail</title>
</head>
<body>
<h1>{{ student.first_name }} {{ student.last_name }}</h1>
<p>Date of Birth: {{ student.date_of_birth }}</p>
<p>Email: {{ student.email }}</p>
<!-- Additional details as needed -->
</body>
</html>

Course_detail.html
<!-- myapp/templates/myapp/course_detail.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Course Detail</title>
</head>
<body>
<h1>{{ course.name }}</h1>
<p>Code: {{ course.code }}</p>

MALLIKARJUNA GD Page183 | 280


21CS62 Course Title : Fullstack Development

<p>Description: {{ course.description }}</p>


<!-- Additional details as needed -->
</body>
</html>

4. Create url

from django.urls import path


from . import views

urlpatterns = [
path('student/<int:student_id>/', views.student_detail,
name='student_detail'),
path('course/<int:course_id>/', views.course_detail,
name='course_detail'),
]

Outside parent one


from django.contrib import admin
from django.urls import path,include

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

6. Create a Superuser

Create a superuser to access the admin interface:

python manage.py createsuperuser

Follow the prompts to set up a username, email, and password.

7. Run the Development Server

Start the development server and navigate to the admin interface


(http://localhost:8000/admin):

python manage.py runserver

MALLIKARJUNA GD Page184 | 280


21CS62 Course Title : Fullstack Development

8. Access Admin Interface and Add Data

Log in using the superuser credentials created earlier.

Add data through the admin interface:

Click on "Students" under "Myapp" to add students.

Click on "Courses" under "Myapp" to add courses

3.3.2 Develop a Model form for a student that contains his topic chosen for the project,
languages used, and duration with a model called project.
let's create a Django model called Project and then create a model form for the Student model
that includes fields for the project topic, languages used, and duration.

Step 1: Define the Project Model

Create a Django model named Project in your app's models.py file:

# myapp/models.py

from django.db import models

class Project(models.Model):

topic = models.CharField(max_length=100)

languages_used = models.CharField(max_length=100)

duration = models.CharField(max_length=50)

def __str__(self):

return self.topic

Step 2: Define the Student Model

Now, let's define the Student model with a foreign key relationship to the Project model:

# myapp/models.py

from django.db import models

class Project(models.Model):

topic = models.CharField(max_length=100)

languages_used = models.CharField(max_length=100)

duration = models.CharField(max_length=50)

def __str__(self):

MALLIKARJUNA GD Page185 | 280


21CS62 Course Title : Fullstack Development

return self.topic

class Student(models.Model):

name = models.CharField(max_length=100)

project = models.ForeignKey(Project, on_delete=models.CASCADE)

def __str__(self):

return self.name

Step 3: Create a ModelForm for Student

Next, create a model form for the Student model with fields for the project topic, languages
used, and duration:

# myapp/forms.py

from django import forms

from .models import Student, Project

class StudentForm(forms.ModelForm):

class Meta:

model = Student

fields = ['name', 'project']

topic = forms.CharField(max_length=100)

languages_used = forms.CharField(max_length=100)

duration = forms.CharField(max_length=50)

Step 4: Display the Form in a Template

Now, you can display the StudentForm in a template to collect input from users:

<!-- myapp/templates/student_form.html -->

<form method="post">

{% csrf_token %}

{{ form.as_p }}

MALLIKARJUNA GD Page186 | 280


21CS62 Course Title : Fullstack Development

<button type="submit">Submit</button>
</form>

Step 5: Handle Form Submission in a View

Define a view function to handle the form submission and save the data to the database:

# myapp/views.py

from django.shortcuts import render, redirect

from .forms import StudentForm

def student_form_view(request):

if request.method == 'POST':

form = StudentForm(request.POST)

if form.is_valid():

student = form.save()

return redirect('success-url') # Redirect to a success page

else:

form = StudentForm()

return render(request, 'student_form.html', {'form': form})

Step 6: Map URL and Configure URLconf

Map the student_form_view to a URL pattern in your project's urls.py file and configure the
URLconf:

# myproject/urls.py

from django.urls import path

from myapp import views

urlpatterns = [

path('student-form/', views.student_form_view, name='student-form'),

# Other URL patterns for your project...

MALLIKARJUNA GD Page187 | 280


21CS62 Course Title : Fullstack Development

You've created a model form for a student with fields for project topic, languages used, and
duration, and integrated it into a Django app. Users can now fill out the form, submit it, and
the data will be saved to the database

3.5 IMPORTANT NOTE


• How do you activate the Django admin interface for your project?
• What are the benefits of using the Django admin interface?
• How do you access the Django admin interface?
• What actions can you perform using the Django admin interface?
• What are the different ways to customize the Django admin interface?
• Can you provide examples of customizations you can make to the admin interface?
• What is form processing in Django?
• Explain the steps involved in processing a form in Django.
• How do you create a feedback form in Django?
• What are some common features of feedback forms?
• How does Django handle form submissions?
• Explain the process of handling form submissions in Django views.
• What is custom validation in Django forms?
• How do you implement custom validation for form fields?
• What are model forms in Django?
• How do you create a model form for a Django model?
• What is URLconf in Django?
• Can you provide some tips or tricks for working with URL patterns in Django?
• How do you include URL patterns from other apps in Django?
• Why would you use URL namespaces when including other URLconfs?

3.6 MCQ
Question 1: How do you activate the Django admin interface for your project?

A) By installing a separate Django package

B) By including 'django.contrib.admin' in INSTALLED_APPS(Correct)

C) By creating a custom admin.py file

D) By defining admin views in views.py

Explanation: Activating the Django admin interface requires adding 'django.contrib.admin' to


the INSTALLED_APPS list in your project's settings.py file.

Question 2: What actions can you perform using the Django admin interface?

A) View database tables

MALLIKARJUNA GD Page188 | 280


21CS62 Course Title : Fullstack Development

B) Add, edit, and delete database records(Correct)

C) Run database queries

D) None of the above

Explanation: The Django admin interface allows administrators to perform CRUD operations
(Create, Read, Update, Delete) on database records.

Question 3: What is a common method for customizing the Django admin interface

A) Editing the Django source code directly

B) Writing custom CSS and JavaScript files

C) Using Django's built-in customization options(Correct)

D) None of the above

Explanation: Django provides built-in options for customizing the admin interface, such as
overriding templates, customizing form fields, and adding custom actions.

Question 4: What is form processing in Django?

A) The process of creating HTML forms

B) The process of handling HTTP requests containing form data(Correct)

C) The process of validating form data

D) The process of styling form elements

Explanation: Form processing in Django involves handling HTTP POST requests sent from HTML
forms and extracting form data from the request.

Question 5: How do you create a feedback form in Django?

A) By defining a model form(Correct)

B) By writing HTML and CSS code manually

C) By using Django's built-in form classes

D) By creating a new Django app

Explanation: In Django, you can create a feedback form by defining a model form that
corresponds to a Feedback model.

Question 6: What happens when a form is submitted in Django?

MALLIKARJUNA GD Page189 | 280


21CS62 Course Title : Fullstack Development

A) The form data is stored in a session variable

B) The form data is sent to a view function for processing(Correct)

C) The form data is directly inserted into the database

D) The form data is encrypted for security

Explanation: When a form is submitted in Django, the form data is sent to a view function
where it can be processed, validated, and saved to the database.

Question 7: How do you implement custom validation for form fields in Django?

A) By using JavaScript validation on the client-side

B) By writing custom validation functions in the views.py file

C) By defining custom validation methods within the form class(Correct)

D) By using Django's built-in validation decorators

Explanation: In Django, you can implement custom validation for form fields by defining custom
validation methods within the form class.

Question 8: What are model forms in Django?

A) Forms generated automatically from database models(Correct)

B) Forms used exclusively for model-based views

C) Forms created using JavaScript frameworks

D) Forms for modeling complex data structures

Explanation: Model forms in Django are forms that are automatically generated based on
database models, making it easy to create forms for database CRUD operations.

Question 9: What is URLconf in Django?

A) A configuration file for defining URL patterns (Correct)

B) A built-in Python module for working with URLs

C) A Django package for handling URL requests

D) None of the above

Explanation: URLconf in Django refers to a configuration file where you define URL patterns for
your Django project.

Question 10: How do you include URL patterns from other apps in Django?

MALLIKARJUNA GD Page190 | 280


21CS62 Course Title : Fullstack Development

A) By copying and pasting URL patterns into the main URLconf

B) By using the `include()` function in the main URLconf(Correct)

C) By importing URL patterns directly from other apps

D) By defining URL patterns in the views.py file

Explanation: In Django, you include URL patterns from other apps by using the `include()`
function in the main URLconf and specifying the module path of the other app's URLconf.

These MCQs cover various aspects of activating, using, customizing Django admin interfaces,
form processing, validation, model forms, URLconf, and including other URLconfs.

MALLIKARJUNA GD Page191 | 280


21CS62 Course Title : Fullstack Development

MODULE-4: GENERIC VIEWS AND DJANGO STATE PERSISTENCE


4.0 USING GENERIC VIEWS
Using generic views in Django is a powerful way to simplify the creation of common views for
tasks such as displaying database objects, handling form submissions, and performing CRUD
operations. Generic views provide pre-built functionality for common patterns, reducing the
amount of code you need to write.

There are two main categories of generic views in Django:

• Class-Based Generic Views

• Function-Based Generic Views

CLASS-BASED GENERIC VIEWS:

Class-based generic views (CBGVs) in Django provide a way to handle common web
development tasks by using reusable, pre-built view classes. This helps developers to avoid
writing repetitive code and allows for more organized and modular code. Instead of writing
functions for each view, you can leverage these classes to handle CRUD (Create, Read, Update,
Delete) operations and more.

Key Components

• Inheritance: CBGVs are built on the principle of inheritance. You can extend base view
classes to create specific views tailored to your needs.
• Mixins: Mixins provide reusable components that add specific behavior to your views. You
can combine multiple mixins to create a view that suits your requirements.
• Methods: Class-based views have specific methods (get, post, put, delete, etc.) that
correspond to HTTP methods, providing a clear structure for handling different types of
requests.

Commonly Used Class-Based Generic Views

1. ListView

Displays a list of objects of a specified model.

Example:

# views.py

from django.views.generic import ListView

from .models import Task

class TaskListView(ListView):

model = Task

MALLIKARJUNA GD Page192 | 280


21CS62 Course Title : Fullstack Development

template_name = 'task_list.html'

context_object_name = 'tasks'

2. DetailView

Displays details of a single object of a specified model.

Example:

# views.py

from django.views.generic import DetailView

from .models import Task

class TaskDetailView(DetailView):

model = Task

template_name = 'task_detail.html'

context_object_name = 'task'

3. CreateView

Provides a form for creating a new object and saves the object upon form submission.

Example:

# views.py

from django.views.generic import CreateView

from .models import Task

from .forms import TaskForm

from django.urls import reverse_lazy

class TaskCreateView(CreateView):

model = Task

form_class = TaskForm

template_name = 'task_form.html'

success_url = reverse_lazy('task_list')

4. UpdateView

Provides a form for updating an existing object and saves the changes upon form submission.

MALLIKARJUNA GD Page193 | 280


21CS62 Course Title : Fullstack Development

Example:

# views.py

from django.views.generic import UpdateView

from .models import Task

from .forms import TaskForm

from django.urls import reverse_lazy

class TaskUpdateView(UpdateView):

model = Task

form_class = TaskForm

template_name = 'task_form.html'

success_url = reverse_lazy('task_list')

5. DeleteView

Provides a confirmation page for deleting an object and deletes the object upon confirmation.

Example:

# views.py

from django.views.generic import DeleteView

from .models import Task

from django.urls import reverse_lazy

class TaskDeleteView(DeleteView):

model = Task

template_name = 'task_confirm_delete.html'

success_url = reverse_lazy('task_list')

Benefits :

• Reusability: Common patterns and functionality are encapsulated in reusable components,


reducing the need to write boilerplate code.
• Organization: Views are organized into classes, making it easier to manage and understand
the code.

MALLIKARJUNA GD Page194 | 280


21CS62 Course Title : Fullstack Development

• Extensibility: You can extend and customize generic views to fit specific requirements by
overriding methods or combining multiple mixins.

How to Use Class-Based Generic Views

Define the Model: Create the Django model that you want to manage.

Create Views: Use the appropriate generic views (e.g., ListView, DetailView) to handle different
operations.

Set Up URLs: Map URLs to your class-based views.

Create Templates: Design templates to render the data.

Example Project Structure

models.py: Define the Task model.

forms.py: Create a TaskForm for handling form submissions.

views.py: Implement class-based views using ListView, DetailView, CreateView, UpdateView,


and DeleteView.

urls.py: Map URLs to the views.

templates: Create HTML templates for listing, displaying, creating, updating, and deleting tasks.

FUNCTION-BASED GENERIC VIEWS

Function-based views (FBVs) in Django are more straightforward and are based on defining
functions that handle specific HTTP requests. While class-based views offer more structure and
reuse through inheritance, function-based views offer simplicity and are easier to understand
for small or simple views.

Key Components:

• Functions: Each view is defined as a function that takes a request object and returns an
HttpResponse object.
• Decorators: Django provides decorators to handle common tasks like authentication.
• Request Methods: Handling different HTTP methods (GET, POST, etc.) is done through
conditional statements within the function.

Common Patterns with Function-Based Views

1. ListView

Displays a list of objects of a specified model.

MALLIKARJUNA GD Page195 | 280


21CS62 Course Title : Fullstack Development

Example:

# views.py

from django.shortcuts import render

from .models import Task

def task_list_view(request):

tasks = Task.objects.all()

return render(request, 'task_list.html', {'tasks': tasks})

2. DetailView

Displays details of a single object of a specified model.

Example:

# views.py

from django.shortcuts import render, get_object_or_404

from .models import Task

def task_detail_view(request, pk):

task = get_object_or_404(Task, pk=pk)

return render(request, 'task_detail.html', {'task': task})

3. CreateView

Provides a form for creating a new object and saves the object upon form submission.

Example:

# views.py

from django.shortcuts import render, redirect

from .forms import TaskForm

def task_create_view(request):

if request.method == 'POST':

form = TaskForm(request.POST)

if form.is_valid():

form.save()

MALLIKARJUNA GD Page196 | 280


21CS62 Course Title : Fullstack Development

return redirect('task_list')

else:

form = TaskForm()

return render(request, 'task_form.html', {'form': form})

4. UpdateView

Provides a form for updating an existing object and saves the changes upon form submission.

Example:

# views.py

from django.shortcuts import render, get_object_or_404, redirect

from .forms import TaskForm

from .models import Task

def task_update_view(request, pk):

task = get_object_or_404(Task, pk=pk)

if request.method == 'POST':

form = TaskForm(request.POST, instance=task)

if form.is_valid():

form.save()

return redirect('task_list')

else:

form = TaskForm(instance=task)

return render(request, 'task_form.html', {'form': form})

5. DeleteView

Provides a confirmation page for deleting an object and deletes the object upon confirmation.

Example:

# views.py

from django.shortcuts import render, get_object_or_404, redirect

MALLIKARJUNA GD Page197 | 280


21CS62 Course Title : Fullstack Development

from .models import Task

def task_delete_view(request, pk):

task = get_object_or_404(Task, pk=pk)

if request.method == 'POST':

task.delete()

return redirect('task_list')

return render(request, 'task_confirm_delete.html', {'task': task})

Benefits

• Simplicity: Easy to understand and write, especially for small or straightforward views.
• Flexibility: Full control over the request and response cycle, making it easier to customize.
• Explicit: The logic for handling different HTTP methods and processing is explicitly defined
within the function.

How to Use Function-Based Views

Define the Model: Create the Django model that you want to manage.

Create Views: Define functions to handle different operations like listing, creating, updating,
and deleting objects.

Set Up URLs: Map URLs to your function-based views.

Create Templates: Design templates to render the data.

Example Project Structure

models.py: Define the Task model.

forms.py: Create a TaskForm for handling form submissions.

views.py: Implement function-based views for listing, displaying, creating, updating, and
deleting tasks.

urls.py: Map URLs to the views.

templates: Create HTML templates for listing, displaying, creating, updating, and deleting tasks.

Mixins:

MALLIKARJUNA GD Page198 | 280


21CS62 Course Title : Fullstack Development

Mixins in Django are a powerful way to add reusable functionality to views. A mixin is a class
that provides methods to other classes through inheritance but is not intended to stand alone.
Mixins can be used to add common behavior to multiple views without duplicating code.

Common Use of Mixins in Django

• Adding Permissions: You can create a mixin to check user permissions before accessing a
view.
• Reusable Logic: Encapsulate common logic that can be shared across different views.

Example of Using Mixins

Let's create a mixin to require that a user be logged in to access certain views. We will then
apply this mixin to our task views.

1. Create a Mixin

Create a file mixins.py in your tasks app directory and define the mixin:

# tasks/mixins.py

from django.contrib.auth.mixins import LoginRequiredMixin

class CustomLoginRequiredMixin(LoginRequiredMixin):

login_url = '/login/' # URL to redirect to if the user is not authenticated

redirect_field_name = 'redirect_to'

This mixin ensures that any view using it requires the user to be logged in.

2. Apply the Mixin to Class-Based Views

Update your views in tasks/views.py to use the mixin:

# tasks/views.py

from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView

from .models import Task

from .forms import TaskForm

from django.urls import reverse_lazy

from .mixins import CustomLoginRequiredMixin

class TaskListView(CustomLoginRequiredMixin, ListView):

MALLIKARJUNA GD Page199 | 280


21CS62 Course Title : Fullstack Development

model = Task

template_name = 'task_list.html'

context_object_name = 'tasks'

class TaskDetailView(CustomLoginRequiredMixin, DetailView):

model = Task

template_name = 'task_detail.html'

context_object_name = 'task'

class TaskCreateView(CustomLoginRequiredMixin, CreateView):

model = Task

form_class = TaskForm

template_name = 'task_form.html'

success_url = reverse_lazy('task_list')

class TaskUpdateView(CustomLoginRequiredMixin, UpdateView):

model = Task

form_class = TaskForm

template_name = 'task_form.html'

success_url = reverse_lazy('task_list')

class TaskDeleteView(CustomLoginRequiredMixin, DeleteView):

model = Task

template_name = 'task_confirm_delete.html'

success_url = reverse_lazy('task_list')

3. Apply the Mixin to Function-Based Views

For function-based views, Django provides decorators, which work similarly to mixins for class-
based views.

Update your function-based views in tasks/views.py to use the login_required decorator:

# tasks/views.py

from django.shortcuts import render, get_object_or_404, redirect

MALLIKARJUNA GD Page200 | 280


21CS62 Course Title : Fullstack Development

from .models import Task

from .forms import TaskForm

from django.contrib.auth.decorators import login_required

from django.utils.decorators import method_decorator

@login_required(login_url='/login/')

def task_list_view(request):

tasks = Task.objects.all()

return render(request, 'task_list.html', {'tasks': tasks})

@login_required(login_url='/login/')

def task_detail_view(request, pk):

task = get_object_or_404(Task, pk=pk)

return render(request, 'task_detail.html', {'task': task})

@login_required(login_url='/login/')

def task_create_view(request):

if request.method == 'POST':

form = TaskForm(request.POST)

if form.is_valid():

form.save()

return redirect('task_list')

else:

form = TaskForm()

return render(request, 'task_form.html', {'form': form})

@login_required(login_url='/login/')

def task_update_view(request, pk):

task = get_object_or_404(Task, pk=pk)

if request.method == 'POST':

form = TaskForm(request.POST, instance=task)

MALLIKARJUNA GD Page201 | 280


21CS62 Course Title : Fullstack Development

if form.is_valid():

form.save()

return redirect('task_list')

else:

form = TaskForm(instance=task)

return render(request, 'task_form.html', {'form': form})

@login_required(login_url='/login/')

def task_delete_view(request, pk):

task = get_object_or_404(Task, pk=pk)

if request.method == 'POST':

task.delete()

return redirect('task_list')

return render(request, 'task_confirm_delete.html', {'task': task})

other mixins are:

In Django, mixins are used extensively to encapsulate and reuse common behavior across
views. Besides authentication-related mixins like LoginRequiredMixin, there are several other
built-in and custom mixins you can use depending on your application's needs. Here are some
commonly used mixins and their purposes:

1. PermissionRequiredMixin

Purpose: Restricts access to a view based on user permissions.

Example: Only allow users with specific permissions (e.g., can_add_task) to access a view.

from django.contrib.auth.mixins import PermissionRequiredMixin

class TaskCreateView(PermissionRequiredMixin, CreateView):

permission_required = 'tasks.add_task'

# Other view properties

2. UserPassesTestMixin

Purpose: Allows you to define custom access logic based on user attributes or conditions.

Example: Check if a user is a member of a specific group before allowing access.

MALLIKARJUNA GD Page202 | 280


21CS62 Course Title : Fullstack Development

from django.contrib.auth.mixins import UserPassesTestMixin

class GroupMembershipMixin(UserPassesTestMixin):

def test_func(self):

return self.request.user.groups.filter(name='Managers').exists()

class TaskUpdateView(GroupMembershipMixin, UpdateView):

# Other view properties

3. FormMixin

Purpose: Provides methods to handle forms in views.

Example: Combine form handling capabilities with other mixins or views.

from django.views.generic.edit import FormMixin

class TaskDetailView(FormMixin, DetailView):

form_class = TaskCommentForm

template_name = 'task_detail.html'

def get_success_url(self):

return reverse('task_detail', kwargs={'pk': self.object.pk})

def post(self, request, *args, **kwargs):

# Handle form submission

form = self.get_form()

if form.is_valid():

# Process form data

return self.form_valid(form)

else:

return self.form_invalid(form)

4. ContextMixin

Purpose: Adds additional context data to views.

Example: Include common context data across multiple views.

from django.views.generic.base import ContextMixin

MALLIKARJUNA GD Page203 | 280


21CS62 Course Title : Fullstack Development

class CommonContextMixin(ContextMixin):

def get_context_data(self, **kwargs):

context = super().get_context_data(**kwargs)

context['site_name'] = 'Task Manager'

return context

5. Multiple Inheritance

Purpose: Combine functionalities from multiple mixins into a single view.

Example: Use mixins for authentication, permissions, and additional context data together.

from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin

from django.views.generic import TemplateView

class DashboardView(LoginRequiredMixin, PermissionRequiredMixin, TemplateView):

template_name = 'dashboard.html'

permission_required = 'tasks.view_dashboard'

Custom Mixins

You can also create your own mixins to encapsulate specific behavior or to combine existing
mixins in Django views. Custom mixins can be useful for handling complex business logic or for
standardizing behavior across different parts of your application.

class CustomMixin:

def some_common_method(self):

# Common logic

pass

class CustomView(CustomMixin, TemplateView):

template_name = 'custom_template.html'

MALLIKARJUNA GD Page204 | 280


21CS62 Course Title : Fullstack Development

4.1 GENERIC VIEWS OF OBJECTS


In Django, Generic Views are pre-built views provided by the Django framework to perform
common tasks such as displaying objects from a database, handling forms, and other typical
web application functionalities. These views are designed to reduce redundancy in code by
providing ready-made solutions for common patterns. Here are some commonly used Generic
Views in Django:

• ListView: Renders a list of objects from a database. Useful for displaying a list of items, such
as a list of blog posts or products.
• DetailView: Displays the details of a single object fetched from the database. For example,
showing the details of a specific blog post or product.
• CreateView: Renders a form for creating a new object and handles the submission of that
form. It typically involves both displaying the form and processing the form submission.
• UpdateView: Renders a form for updating an existing object and handles the submission of
the updated form.
• DeleteView: Displays a confirmation page for deleting an object and handles the deletion
process upon confirmation.
• FormView: Displays a form and handles form submission. It's more customizable than
CreateView and UpdateView, making it suitable for cases where you need more control
over the form processing logic.
• TemplateView: Renders a template without involving models or forms directly. It's useful
for displaying static content or rendering pages that don't require data from a database.

Using Generic Views simplifies development by providing reusable components that handle
common tasks. They follow the DRY (Don't Repeat Yourself) principle and encourage best
practices in Django development. Each Generic View typically requires minimal configuration
and can be customized by overriding class attributes or methods to fit specific requirements.
Step 1: Import Generic Views

First, import the necessary generic views from Django's views.generic module in your views.py
file.

from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView

Step 2: Define URL Patterns

Define URL patterns for your views in your project's urls.py file. Map each view to a URL pattern
using Django's path() function.

from django.urls import path

from .views import MyListView, MyDetailView, MyCreateView, MyUpdateView, MyDeleteView

MALLIKARJUNA GD Page205 | 280


21CS62 Course Title : Fullstack Development

urlpatterns = [

path('my-list/', MyListView.as_view(), name='my-list'),

path('my-detail/<int:pk>/', MyDetailView.as_view(), name='my-detail'),

path('my-create/', MyCreateView.as_view(), name='my-create'),

path('my-update/<int:pk>/', MyUpdateView.as_view(), name='my-update'),

path('my-delete/<int:pk>/', MyDeleteView.as_view(), name='my-delete'),

Step 3: Define Views

Define your views by subclassing the appropriate generic views and specifying the model and
template attributes.

from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView

from .models import MyModel

class MyListView(ListView):

model = MyModel

template_name = 'myapp/my_model_list.html'

class MyDetailView(DetailView):

model = MyModel

template_name = 'myapp/my_model_detail.html'

class MyCreateView(CreateView):

model = MyModel

template_name = 'myapp/my_model_form.html'

fields = ['field1', 'field2']

class MyUpdateView(UpdateView):

model = MyModel

MALLIKARJUNA GD Page206 | 280


21CS62 Course Title : Fullstack Development

template_name = 'myapp/my_model_form.html'

fields = ['field1', 'field2']

class MyDeleteView(DeleteView):

model = MyModel

template_name = 'myapp/my_model_confirm_delete.html'

success_url = '/my-list/'

Step 4: Create Templates

Create templates for your views if they don't already exist. These templates should match the
template_name attributes specified in your views.

Step 5: Access URLs

Access the URLs associated with your generic views in a web browser or link to them in your
templates using Django's {% url %} template tag.

By using generic views of objects, you can quickly create views for common CRUD operations
without having to write a lot of boilerplate code. This can lead to cleaner, more maintainable
code and faster development times.

4.2 EXTENDING GENERIC VIEWS OF OBJECTS


Extending generic views of objects in Django allows you to customize the behavior and
appearance of these views to better suit your application's requirements. You can extend
generic views by overriding methods, attributes, or by combining them with mixins. Here's how
to extend generic views of objects:

Step 1: Define Your Custom View

Define a custom view by subclassing the desired generic view and overriding methods or
attributes as needed.

from django.views.generic import ListView

from .models import MyModel

class CustomListView(ListView):

model = MyModel

template_name = 'myapp/my_custom_list.html'

def get_queryset(self):

MALLIKARJUNA GD Page207 | 280


21CS62 Course Title : Fullstack Development

# Customize queryset as needed

queryset = super().get_queryset()

return queryset.filter(some_condition=True)

Step 2: Define URL Pattern

Define a URL pattern for your custom view in your project's urls.py file.

from django.urls import path

from .views import CustomListView

urlpatterns = [

path('my-custom-list/', CustomListView.as_view(), name='my-custom-list'),

Step 3: Create Template

Create a template for your custom view if it doesn't already exist. This template should match
the template_name attribute specified in your custom view.

Step 4: Access URL

Access the URL associated with your custom view in a web browser or link to it in your
templates using Django's {% url %} template tag.

Extending with Mixins

You can also extend generic views by combining them with mixins. Mixins are reusable
components that provide additional functionality to views.

from django.views.generic import ListView

from django.contrib.auth.mixins import LoginRequiredMixin

from .models import MyModel

class CustomListView(LoginRequiredMixin, ListView):

model = MyModel

template_name = 'myapp/my_custom_list.html'

In this example, LoginRequiredMixin is a mixin that ensures the user is authenticated before
accessing the view.

MALLIKARJUNA GD Page208 | 280


21CS62 Course Title : Fullstack Development

Benefits of Extending Generic Views

• Customization: You can tailor views to meet specific requirements by overriding


methods or attributes.
• Reusability: Custom views and mixins can be reused across multiple views, promoting
code reuse.
• Flexibility: Extending generic views allows you to adapt them to various scenarios
without starting from scratch.

By extending generic views, you can build upon existing functionality to create views that
precisely meet your application's needs while maintaining the benefits of generic views.

4.3 EXTENDING GENERIC VIEWS


Extending generic views in Django allows you to customize and add functionality to existing
generic views to better suit your application's requirements. You can extend generic views by
subclassing them and overriding methods or attributes, or by combining them with mixins.
Here's how to extend generic views:

Step 1: Define Your Custom View

Define a custom view by subclassing the desired generic view and overriding methods or
attributes as needed.

from django.views.generic import ListView

from .models import MyModel

class CustomListView(ListView):

model = MyModel

template_name = 'myapp/my_custom_list.html'

def get_queryset(self):

# Customize queryset as needed

queryset = super().get_queryset()

return queryset.filter(some_condition=True)

Step 2: Define URL Pattern

Define a URL pattern for your custom view in your project's urls.py file.

from django.urls import path

MALLIKARJUNA GD Page209 | 280


21CS62 Course Title : Fullstack Development

from .views import CustomListView

urlpatterns = [

path('custom-list/', CustomListView.as_view(), name='custom-list'),

Step 3: Create Template

Create a template for your custom view if it doesn't already exist. This template should match
the template_name attribute specified in your custom view.

Step 4: Access URL

Access the URL associated with your custom view in a web browser or link to it in your
templates using Django's {% url %} template tag.

Extending with Mixins

You can also extend generic views by combining them with mixins. Mixins are reusable
components that provide additional functionality to views.

from django.views.generic import ListView

from django.contrib.auth.mixins import LoginRequiredMixin

from .models import MyModel

class CustomListView(LoginRequiredMixin, ListView):

model = MyModel

template_name = 'myapp/my_custom_list.html'

In this example, LoginRequiredMixin is a mixin that ensures the user is authenticated before
accessing the view.

4.4 MIME TYPES


MIME (Multipurpose Internet Mail Extensions) types are a standard way of indicating the type
of data that a file contains on the Internet. MIME types are used by web servers and browsers
to interpret and handle different types of files appropriately. Here are some common MIME
types and their descriptions:

• text/html: Represents HTML files, which are used to create web pages.
• text/css: Represents Cascading Style Sheets (CSS) files, which are used to style HTML
documents.
• application/javascript: Represents JavaScript files, which are used to add interactivity and
dynamic behavior to web pages.

MALLIKARJUNA GD Page210 | 280


21CS62 Course Title : Fullstack Development

• image/jpeg: Represents JPEG image files, which are commonly used for photographs and
other images with complex colors and details.
• image/png: Represents PNG image files, which are commonly used for images with
transparent backgrounds or simple graphics.
• application/pdf: Represents PDF (Portable Document Format) files, which are used for
documents that need to be displayed and printed consistently across different platforms.
• application/json: Represents JSON (JavaScript Object Notation) files, which are used for
exchanging data between a server and a web application.
• application/xml: Represents XML (eXtensible Markup Language) files, which are used for
storing and transporting structured data.
• text/plain: Represents plain text files, which contain unformatted text without any special
styling or formatting.
• audio/mpeg: Represents MP3 audio files, which are commonly used for storing and playing
music and other audio recordings.

These are just a few examples of MIME types, and there are many more in use on the Internet.
MIME types help web servers and browsers determine how to handle different types of files,
such as displaying them in a web browser, downloading them to a user's device, or executing
them as scripts.

In Django, you can work with MIME types mainly in two scenarios: when serving static files and
when handling file uploads or downloads. Here's how you can use MIME types in Django:

Serving Static Files

When serving static files (e.g., CSS, JavaScript, images), Django's built-in static template tag
automatically sets the appropriate MIME type for the files based on their file extensions. You
typically don't need to handle MIME types explicitly in this case.

<!-- Example usage of static template tag -->

<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">

<script type="application/javascript" src="{% static 'js/script.js' %}"></script>

<img src="{% static 'images/logo.png' %}" alt="Logo">

Handling File Uploads or Downloads

When handling file uploads or downloads in Django, you may need to set or determine the
MIME type of the files manually. Here's how you can do it:

Setting MIME Type for File Downloads

When serving files for download, you can set the appropriate MIME type using Django's
FileResponse or HttpResponse class along with the content_type parameter.

MALLIKARJUNA GD Page211 | 280


21CS62 Course Title : Fullstack Development

from django.http import FileResponse

def download_file(request):

# Open the file

file_path = '/path/to/file.pdf'

with open(file_path, 'rb') as file:

# Set the MIME type explicitly

response = FileResponse(file, content_type='application/pdf')

# Optionally, set the filename for the downloaded file

response['Content-Disposition'] = 'attachment; filename="file.pdf"'

return response

Determining MIME Type for File Uploads

When handling file uploads, you can determine the MIME type of the uploaded file using
libraries such as python-magic or mimetypes.

import magic

def handle_file_upload(request):

uploaded_file = request.FILES['file']

# Determine the MIME type of the uploaded file

mime_type = magic.from_buffer(uploaded_file.read(), mime=True)

# Process the uploaded file based on its MIME type

if mime_type == 'application/pdf':

# Handle PDF file

pass

elif mime_type == 'image/jpeg':

# Handle JPEG image file

pass

else:

# Handle other file types

MALLIKARJUNA GD Page212 | 280


21CS62 Course Title : Fullstack Development

pass

• Django automatically handles MIME types for static files.


• For file downloads, you can set the MIME type explicitly using FileResponse or
HttpResponse.
• For file uploads, you can determine the MIME type using libraries like python-magic or
mimetypes.

4.5 GENERATING NON-HTML CONTENTS LIKE CSV AND PDF


To generate non-HTML contents like CSV and PDF in Django, you can follow these steps:

CSV Generation:

• Define a View: Create a Django view that generates CSV data dynamically.
• Use csv Module: Import the csv module and use its functionalities to write data to a CSV
file.
• Set HTTP Response Headers: Set appropriate HTTP response headers to specify that the
response is a CSV file.
• Return Response: Return the CSV data as an HTTP response.

PDF Generation:

• Define a View: Create a Django view that generates PDF data dynamically.
• Use a PDF Generation Library: Use a PDF generation library like reportlab to create PDF
documents.
• Set HTTP Response Headers: Set appropriate HTTP response headers to specify that the
response is a PDF file.
• Return Response: Return the PDF data as an HTTP response.

Example Code:

Generate CSV and PDF files in Django:

import csv

from django.http import HttpResponse

from reportlab.lib import colors

from reportlab.lib.pagesizes import letter

from reportlab.platypus import SimpleDocTemplate, Table, TableStyle

# CSV generation view

def generate_csv(request):

response = HttpResponse(content_type='text/csv')

MALLIKARJUNA GD Page213 | 280


21CS62 Course Title : Fullstack Development

response['Content-Disposition'] = 'attachment; filename="data.csv"'

writer = csv.writer(response)

writer.writerow(['Name', 'Age', 'Email']) # CSV header row

writer.writerow(['John Doe', 30, '[email protected]']) # Example data row

writer.writerow(['Jane Smith', 25, '[email protected]']) # Example data row

return response

# PDF generation view

def generate_pdf(request):

response = HttpResponse(content_type='application/pdf')

response['Content-Disposition'] = 'attachment; filename="data.pdf"'

data = [

['Name', 'Age', 'Email'],

['Mallikarjuna', 30, '[email protected]'],

['Mohan', 25, '[email protected]']

# Generate PDF

doc = SimpleDocTemplate(response, pagesize=letter)

table = Table(data)

style = TableStyle([('BACKGROUND', (0, 0), (-1, 0), colors.grey),

('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),

('ALIGN', (0, 0), (-1, -1), 'CENTER'),

('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),

('BOTTOMPADDING', (0, 0), (-1, 0), 12),

('BACKGROUND', (0, 1), (-1, -1), colors.beige),

('GRID', (0, 0), (-1, -1), 1, colors.black)])

table.setStyle(style)

MALLIKARJUNA GD Page214 | 280


21CS62 Course Title : Fullstack Development

doc.build([table])

return response

In this example:

• The generate_csv view generates a CSV file with some example data.
• The generate_pdf view generates a PDF file with some example data using the
reportlab library.

You can map these views to URLs in your Django app's urls.py to allow users to download CSV
and PDF files when they visit those URLs.

4.6 SYNDICATION FEED FRAMEWORK


The syndication feed framework in Django allows you to generate syndication feeds (such as
RSS or Atom feeds) for your site's content. These feeds can be consumed by users or other
applications to stay updated with the latest content from your site.

Here's how you can use the syndication feed framework in Django:

Step 1: Define Feeds

First, define feed classes in a feeds.py file within your Django app. Each feed class represents a
different type of feed (e.g., RSS or Atom) and specifies the content to include in the feed.

from django.contrib.syndication.views import Feed

from .models import Post

class LatestPostsFeed(Feed):

title = "My Blog"

link = "/blog/"

description = "Latest posts from My Blog"

def items(self):

return Post.objects.order_by('-published_date')[:5]

def item_title(self, item):

return item.title

def item_description(self, item):

return item.content

Step 2: Configure URL Patterns

MALLIKARJUNA GD Page215 | 280


21CS62 Course Title : Fullstack Development

Next, configure URL patterns in your project's urls.py file to map URLs to feed views. You can
use Django's Feed class-based views directly in URL patterns.

from django.urls import path

from myapp.feeds import LatestPostsFeed

urlpatterns = [

path('latest/feed/', LatestPostsFeed(), name='latest-posts-feed'),

Step 3: Include Feed URLs

Include the URLs for your feeds in your project's main URLconf by using Django's include()
function.

from django.urls import path, include

urlpatterns = [

# Other URL patterns for your project...

path('feeds/', include('myapp.feeds')),

Step 4: Access Feeds

Once you've set up the feed URLs, users or other applications can access the feeds by visiting
the corresponding URLs in a web browser or by consuming them programmatically.

For example, the latest posts feed can be accessed at http://example.com/feeds/latest/feed/.

Customizing Feeds

You can customize the content and appearance of your feeds by subclassing Django's Feed class
and overriding methods such as items(), item_title(), and item_description(). This allows you to
tailor the feeds to include specific content from your models and control how that content is
presented in the feed.

• Define feed classes in a feeds.py file within your Django app.


• Configure URL patterns to map URLs to feed views.
• Include feed URLs in your project's main URLconf.
• Customize feed content and appearance by subclassing Django's Feed class.

By using the syndication feed framework in Django, you can easily generate and serve
syndication feeds for your site's content, making it more accessible to users and other
applications.

MALLIKARJUNA GD Page216 | 280


21CS62 Course Title : Fullstack Development

4.7 SITEMAP FRAMEWORK


The sitemap framework in Django allows you to generate XML sitemap files for your website.
These sitemap files help search engines discover and index the pages on your site more
efficiently.

Here's how you can use the sitemap framework in Django:

Step 1: Define Sitemaps

First, define sitemap classes in a sitemaps.py file within your Django app. Each sitemap class
represents a different section or type of content on your site and specifies the URLs to include
in the sitemap.

from django.contrib.sitemaps import Sitemap

from .models import Post

class PostSitemap(Sitemap):

changefreq = 'weekly'

priority = 0.9

def items(self):

return Post.objects.all()

def lastmod(self, obj):

return obj.modified_date

Step 2: Configure URL Patterns

Next, configure URL patterns in your project's urls.py file to map URLs to sitemap views. You
can use Django's Sitemap class-based views directly in URL patterns.

from django.urls import path

from django.contrib.sitemaps.views import sitemap

from myapp.sitemaps import PostSitemap

sitemaps = {

'posts': PostSitemap,

urlpatterns = [

MALLIKARJUNA GD Page217 | 280


21CS62 Course Title : Fullstack Development

path('sitemap.xml', sitemap, {'sitemaps': sitemaps},


name='django.contrib.sitemaps.views.sitemap'),

Step 3: Register Sitemaps (Optional)

If your site has multiple sitemap classes, you can register them with Django's Sitemap class in
your project's urls.py file.

from django.contrib.sitemaps import Sitemap

from .sitemaps import PostSitemap, ProductSitemap

sitemaps = {

'posts': PostSitemap,

'products': ProductSitemap,

urlpatterns = [

path('sitemap.xml', sitemap, {'sitemaps': sitemaps},


name='django.contrib.sitemaps.views.sitemap'),

Step 4: Access Sitemaps

Once you've set up the sitemap URLs, search engines and other tools can access the sitemap
files by visiting the corresponding URLs.

For example, the sitemap can be accessed at http://example.com/sitemap.xml.

Customizing Sitemaps

You can customize the content and appearance of your sitemaps by subclassing Django's
Sitemap class and overriding methods such as items() and lastmod(). This allows you to tailor
the sitemaps to include specific URLs and control how they are presented to search engines.

• Define sitemap classes in a sitemaps.py file within your Django app.


• Configure URL patterns to map URLs to sitemap views.
• Optionally, register multiple sitemap classes with Django's Sitemap class.
• Customize sitemap content and appearance by subclassing Django's Sitemap class.

By using the sitemap framework in Django, you can easily generate XML sitemap files for your
website, making it easier for search engines to discover and index your site's content.

MALLIKARJUNA GD Page218 | 280


21CS62 Course Title : Fullstack Development

4.8 COOKIES, SESSIONS


Cookies and sessions are both mechanisms used in web development to maintain stateful
information between HTTP requests. They serve similar purposes but differ in how they store
and manage data. Here's a brief overview of cookies and sessions in web development:

Cookies: Cookies are small pieces of data that are stored on the client's browser. They are sent
to the server with every HTTP request, allowing the server to track and identify individual users.

Storage: Cookies are stored on the client's browser as key-value pairs. They have a limited size
(typically a few kilobytes) and can be set to expire after a certain period or persist indefinitely.

Usage: Cookies are commonly used for user authentication, tracking user preferences, session
management, and personalization.

Security: Cookies can be vulnerable to security risks such as cross-site scripting (XSS) and cross-
site request forgery (CSRF) if not handled properly. Secure and HttpOnly flags can be set to
mitigate these risks.

Sessions:

Sessions are server-side data storage mechanisms that maintain stateful information about a
user's interactions with a website. Each session is associated with a unique session identifier
(session ID) that is sent to the client as a cookie.

Storage: Session data is stored on the server, typically in memory, a database, or a distributed
caching system. Only the session ID is stored on the client's browser as a cookie.

Usage: Sessions are commonly used for user authentication, maintaining shopping cart
information, tracking user activity, and storing temporary data across multiple HTTP requests.

Security: Sessions are generally considered more secure than cookies because session data is
stored on the server and not accessible to clients. However, session hijacking and session
fixation attacks are still possible if proper security measures are not implemented.

Comparison:

• Data Storage: Cookies store data on the client's browser, while sessions store data on
the server.
• Persistence: Cookies can persist indefinitely or have an expiration date, while sessions
typically expire after a period of inactivity or when the user logs out.
• Size Limit: Cookies have size limitations (a few kilobytes), while sessions can store
larger amounts of data depending on server capacity.
• Security: Sessions are generally considered more secure than cookies because session
data is stored on the server and not accessible to clients. However, both cookies and
sessions can be vulnerable to security risks if not handled properly.

MALLIKARJUNA GD Page219 | 280


21CS62 Course Title : Fullstack Development

The cookies and sessions are both essential tools for maintaining stateful information in web
applications. They serve similar purposes but have different implementations and use cases.
Cookies are suitable for storing small amounts of data on the client's browser, while sessions
are better suited for storing larger amounts of data on the server. It's essential to understand
the differences between cookies and sessions and use them appropriately based on your
application's requirements and security considerations.

django step by step example for cookies and session handling

Sure, here's a step-by-step example of how to handle cookies and sessions in Django:

Step 1: Set Up a Django Project

Create a new Django project and an app within the project.

django-admin startproject myproject

cd myproject

python manage.py startapp myapp

Step 2: Define Views

Define views in your views.py file to demonstrate cookies and session handling.

from django.shortcuts import render

from django.http import HttpResponse

def set_cookie(request):

response = HttpResponse("Cookie set successfully!")

response.set_cookie('my_cookie', 'cookie_value')

return response

def get_cookie(request):

my_cookie = request.COOKIES.get('my_cookie')

return HttpResponse(f"Value of my_cookie: {my_cookie}")

def set_session(request):

request.session['my_session'] = 'session_value'

MALLIKARJUNA GD Page220 | 280


21CS62 Course Title : Fullstack Development

return HttpResponse("Session set successfully!")

def get_session(request):

my_session = request.session.get('my_session')

return HttpResponse(f"Value of my_session: {my_session}")

Step 3: Configure URLs

Configure URL patterns in your urls.py file to map URLs to the defined views.

from django.urls import path

from .views import set_cookie, get_cookie, set_session, get_session

urlpatterns = [

path('set-cookie/', set_cookie, name='set-cookie'),

path('get-cookie/', get_cookie, name='get-cookie'),

path('set-session/', set_session, name='set-session'),

path('get-session/', get_session, name='get-session'),

Step 4: Configure Session Middleware

Ensure that Django's session middleware is enabled in your settings.py file.

MIDDLEWARE = [

# Other middleware...

'django.contrib.sessions.middleware.SessionMiddleware',

# Other middleware...

Step 5: Run Migrations

Run Django migrations to apply changes to your database.

python manage.py migrate

Step 6: Run the Development Server

MALLIKARJUNA GD Page221 | 280


21CS62 Course Title : Fullstack Development

Start the Django development server and navigate to the URLs defined in your views.

python manage.py runserver

Step 7: Test Cookie and Session Handling

Visit /set-cookie/ to set a cookie.

Visit /get-cookie/ to retrieve the value of the cookie.

Visit /set-session/ to set a session variable.

Visit /get-session/ to retrieve the value of the session variable.

This example demonstrates how to handle cookies and sessions in Django. Cookies are set using
the set_cookie() method and retrieved using the COOKIES attribute of the request object.
Sessions are set using dictionary-like syntax (request.session['key']) and retrieved using the
session attribute of the request object. Ensure that Django's session middleware is enabled to
use session functionality.

django session object example

let's create a simple Django example to demonstrate the usage of session objects:

Step 1: Define Views

In your views.py, define views to set and retrieve session data.

from django.shortcuts import render

from django.http import HttpResponse

def set_session(request):

request.session['username'] = 'john_doe'

return HttpResponse("Session data set successfully!")

def get_session(request):

username = request.session.get('username', 'Guest')

return HttpResponse(f"Hello, {username}!")

Step 2: Configure URLs

Define URL patterns in your urls.py to map URLs to the defined views.

from django.urls import path

from .views import set_session, get_session

MALLIKARJUNA GD Page222 | 280


21CS62 Course Title : Fullstack Development

urlpatterns = [

path('set-session/', set_session, name='set-session'),

path('get-session/', get_session, name='get-session'),

Step 3: Configure Session Middleware

Ensure Django's session middleware is enabled in your settings.py.

MIDDLEWARE = [

# Other middleware...

'django.contrib.sessions.middleware.SessionMiddleware',

# Other middleware...

Step 4: Run Migrations

Run Django migrations to apply changes to your database.

python manage.py migrate

Step 5: Run the Development Server

Start the Django development server.

python manage.py runserver

Step 6: Test Session Handling

Visit /set-session/ to set a session variable.

Visit /get-session/ to retrieve the value of the session variable.

This example demonstrates how to set and retrieve session data in Django. Session data is
stored as dictionary-like objects (request.session) and persists across multiple requests for the
same user. Ensure that Django's session middleware is enabled to use session functionality.

4.9 USERS AND AUTHENTICATION


Users and authentication are fundamental components of web applications, including those
built with Django. Here's an overview along with some key aspects:

Users:

MALLIKARJUNA GD Page223 | 280


21CS62 Course Title : Fullstack Development

• User Model: Django provides a built-in user model (django.contrib.auth.models.User)


to manage users.
• User Registration: Users can register on the website by providing necessary details like
username, email, and password.
• User Profile: Additional information about users can be stored in a profile model
associated with the user.
• User Management: Administrators can manage users, including creating, updating, and
deleting user accounts.

Authentication:

• Login: Users authenticate themselves by providing their credentials (username/email


and password).
• Logout: Users can log out of their accounts to terminate their authenticated session.
• Session Management: Django manages user sessions using session cookies and
provides utilities to manage session data.
• Password Management: Users can reset their passwords if they forget them. Django
provides built-in views and forms for password reset functionality.

Permissions and Authorization:

• Permissions: Django provides a permission system to control access to views and


functionality within the application.
• Groups: Users can be organized into groups, and permissions can be assigned to groups
instead of individual users.
• Authorization: Views can be protected using decorators or mixins to ensure that only
authenticated users or users with specific permissions can access them.

Example Code:

an example of how to implement user authentication in Django:

from django.contrib.auth import authenticate, login, logout

from django.contrib.auth.models import User

from django.shortcuts import render, redirect

from django.contrib.auth.decorators import login_required

def user_login(request):

if request.method == 'POST':

username = request.POST['username']

MALLIKARJUNA GD Page224 | 280


21CS62 Course Title : Fullstack Development

password = request.POST['password']

user = authenticate(request, username=username, password=password)

if user is not None:

login(request, user)

return redirect('home')

else:

return render(request, 'login.html', {'error': 'Invalid username or password'})

else:

return render(request, 'login.html')

@login_required

def user_logout(request):

logout(request)

return redirect('login')

@login_required

def home(request):

return render(request, 'home.html')

In this example:

The user_login view handles user login authentication.

The user_logout view logs out the authenticated user.

The home view is protected with the @login_required decorator to ensure only authenticated
users can access it.

Users and authentication are essential components of web applications. Django provides
robust built-in functionality for managing users, authenticating users, and controlling access to
views and functionality. Understanding and implementing user authentication properly are
crucial for building secure and user-friendly web applications

MALLIKARJUNA GD Page225 | 280


21CS62 Course Title : Fullstack Development

4.10 PRACTICES
4.10.1 For student enrolment developed in Module 2, create a generic class view
that displays a list of students and a detail view that displays student details for any
selected student in the list.
To create a generic class-based view for displaying a list of students and another for displaying
student details, you can follow these steps:

Step 1: Define Models

Assuming you have a Student model defined in your models.py:

from django.db import models

class Student(models.Model):

name = models.CharField(max_length=100)

roll_number = models.CharField(max_length=20)

# Add other fields as needed

Step 2: Define URLs

Define URL patterns in your urls.py file to map URLs to the class-based views.

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 3: Define Class-Based Views

Create class-based views in your views.py file using Django's generic views.

from django.views.generic import ListView, DetailView

from .models import Student

class StudentListView(ListView):

model = Student

MALLIKARJUNA GD Page226 | 280


21CS62 Course Title : Fullstack Development

template_name = 'student_list.html'

context_object_name = 'students' # Optional: specify the context variable name

class StudentDetailView(DetailView):

model = Student

template_name = 'student_detail.html'

context_object_name = 'student' # Optional: specify the context variable name

Step 4: Create Templates

Create HTML templates for displaying the list of students (student_list.html) and the student
details (student_detail.html).

student_list.html:

<!DOCTYPE html>

<html>

<head>

<title>Student List</title>

</head>

<body>

<h1>Student List</h1>

<ul>

{% for student in students %}

<li><a href="{% url 'student-detail' student.pk %}">{{ student.name }}</a></li>

{% endfor %}

</ul>

</body>

</html>

student_detail.html:

<!DOCTYPE html>

<html>

MALLIKARJUNA GD Page227 | 280


21CS62 Course Title : Fullstack Development

<head>

<title>Student Details</title>

</head>

<body>

<h1>Student Details</h1>

<p><strong>Name:</strong> {{ student.name }}</p>

<p><strong>Roll Number:</strong> {{ student.roll_number }}</p>

<!-- Add other student details as needed -->

</body>

</html>

Step 5: Test the Views

Run your Django server and navigate to the URLs /students/ to view the list of students and
/students/<pk>/ to view the details of a specific student.

u've created generic class-based views for displaying a list of students and their details. These
views leverage Django's built-in functionality, reducing the amount of code you need to write.

4.10.2 Develop an example Django app that performs CSV and PDF generation for
any models created in the previous laboratory component
To create a Django app that performs CSV and PDF generation for any models, you can follow
these steps:

Step 1: Install Required Libraries

Install the necessary libraries for CSV and PDF generation. For CSV, you can use the built-in csv
module in Python. For PDF generation, you can use the reportlab library.

pip install reportlab

Step 2: Define Views for CSV and PDF Generation

In your Django app's views.py, define views for CSV and PDF generation.

import csv

from django.http import HttpResponse

from reportlab.lib import colors

MALLIKARJUNA GD Page228 | 280


21CS62 Course Title : Fullstack Development

from reportlab.lib.pagesizes import letter

from reportlab.platypus import SimpleDocTemplate, Table, TableStyle

from .models import YourModel

def generate_csv(request):

response = HttpResponse(content_type='text/csv')

response['Content-Disposition'] = 'attachment; filename="data.csv"'

writer = csv.writer(response)

writer.writerow(['Field 1', 'Field 2', 'Field 3']) # Add column headers

queryset = YourModel.objects.all()

for obj in queryset:

writer.writerow([obj.field1, obj.field2, obj.field3]) # Replace field1, field2, field3 with


actual field names

return response

def generate_pdf(request):

response = HttpResponse(content_type='application/pdf')

response['Content-Disposition'] = 'attachment; filename="data.pdf"'

queryset = YourModel.objects.all()

# Generate PDF

doc = SimpleDocTemplate(response, pagesize=letter)

data = [[obj.field1, obj.field2, obj.field3] for obj in queryset] # Replace field1, field2, field3
with actual field names

table = Table(data)

style = TableStyle([('BACKGROUND', (0, 0), (-1, 0), colors.grey),

('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),

('ALIGN', (0, 0), (-1, -1), 'CENTER'),

('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),

MALLIKARJUNA GD Page229 | 280


21CS62 Course Title : Fullstack Development

('BOTTOMPADDING', (0, 0), (-1, 0), 12),

('BACKGROUND', (0, 1), (-1, -1), colors.beige),

('GRID', (0, 0), (-1, -1), 1, colors.black)])

table.setStyle(style)

doc.build([table])

return response

Step 3: Define URLs

Define URL patterns in your app's urls.py to map URLs to the defined views.

from django.urls import path

from .views import generate_csv, generate_pdf

urlpatterns = [

path('generate-csv/', generate_csv, name='generate-csv'),

path('generate-pdf/', generate_pdf, name='generate-pdf'),

Step 4: Test the Views

Run your Django server and navigate to /generate-csv/ and /generate-pdf/ to download the
generated CSV and PDF files, respectively.

With these steps, you've created views in your Django app that can generate CSV and PDF files
based on data from your models. These views can be easily extended to handle other models
or customized to suit your specific requirements.

4.10 IMPORTANT NOTE


• What are generic views in Django?
• Explain the advantages of using generic views over writing views from scratch.
• List and briefly explain some of the generic view classes provided by Django.
• How do you customize generic views in Django?
• Can you use mixins with generic views? Explain with an example.
• What is meant by extending generic views in Django?
• How can you extend generic views in Django? Provide examples.
• Explain the concept of view inheritance in Django.
• What are some common use cases for extending generic views?
• How do you handle data processing and rendering in extended generic views?
• What are the benefits of extending generic views?

MALLIKARJUNA GD Page230 | 280


21CS62 Course Title : Fullstack Development

• Explain how you can add additional functionality to generic views by extending them.
• Provide examples of scenarios where you might need to extend generic views.
• How do you handle form processing and validation in extended generic views?
• Can you explain the concept of view composition in Django?
• What are MIME types and why are they important in web development?
• Explain the role of MIME types in HTTP headers.
• List and briefly describe some common MIME types used on the web.
• How do you set MIME types in Django views?
• Discuss the security implications of handling MIME types in web applications.
• Why would you need to generate non-HTML content like CSV and PDF in a web
application?
• What are the advantages of generating CSV and PDF files dynamically?
• Explain the process of generating CSV files in Django.
• How do you generate PDF files in Django? Mention any libraries you can use.
• Discuss the considerations for handling large datasets when generating CSV and PDF
files.
• What is the syndication feed framework in Django?
• Explain the purpose of syndication feeds in web development.
• How do you create and configure syndication feeds in Django?
• Discuss the different types of syndication feeds supported by Django.
• Can you provide examples of how syndication feeds are used in real-world
applications?
• What is the sitemap framework in Django?
• Explain the importance of sitemaps for search engine optimization (SEO).
• How do you create and configure sitemaps in Django?
• Discuss the benefits of using the sitemap framework for large websites.
• Can you explain how sitemaps are generated and served to search engines?
• What are cookies and sessions in web development?
• Explain the differences between cookies and sessions.
• How are cookies and sessions managed in Django?
• Discuss the security considerations when using cookies and sessions.
• Provide examples of scenarios where cookies and sessions are used in web
applications.
• How does user authentication work in Django?
• Explain the role of the built-in authentication system in Django.
• How do you create and manage user accounts in Django?
• Discuss the different authentication mechanisms supported by Django.
• Can you explain the concept of authorization and how it relates to authentication in
web applications?

MALLIKARJUNA GD Page231 | 280


21CS62 Course Title : Fullstack Development

4.11 MCQ
Question 1. What is the purpose of Django's syndication feed framework?

a) To generate XML sitemaps

b) To generate RSS or Atom feeds(Correct)

c) To handle user authentication

d) To generate PDF files

Explanation: The syndication feed framework in Django is used to generate RSS or Atom feeds,
allowing users or other applications to subscribe to and consume updates from your site.

Question 2. Which of the following MIME types is used for JavaScript files?

a) text/html

b) application/json

c) application/javascript(Correct)

d) image/png

Explanation: JavaScript files are typically served with the MIME type application/javascript.

Question 3. How can you generate a CSV file dynamically in Django?

a) Using Django's built-in csv module

b) Using Django's HttpResponse class

c) Using Django's FileResponse class

d) All of the above (Correct)

Explanation: You can generate a CSV file dynamically in Django using the built-in csv module
along with either HttpResponse or FileResponse class.

Question 4. What is the role of cookies in web development?

a) To store session data on the server

b) To store session data on the client

c) To authenticate users

d) To generate XML sitemaps

Explanation: Cookies are used to store small pieces of data on the client's browser, including
session data, preferences, and tracking information.

MALLIKARJUNA GD Page232 | 280


21CS62 Course Title : Fullstack Development

Question 5. Which of the following is NOT a valid method of extending generic views in Django?

a) Subclassing

b) Using mixins

c) Function composition

d) View inheritance

Explanation: Function composition is not a method of extending generic views in Django.


Instead, you can use subclassing, mixins, or view inheritance.

Question 6. What is the purpose of Django's sitemap framework?

a) To generate RSS or Atom feeds

b) To generate XML sitemaps(Correct)

c) To handle user authentication

d) To generate PDF files

Explanation: Django's sitemap framework is used to generate XML sitemaps, which help search
engines discover and index the pages on your site.

Question 7. How are sessions managed in Django?

a) By storing session data in cookies

b) By storing session data in the database

c) By storing session data in server memory

d) All of the above(Correct)

Explanation: Sessions in Django can be managed by storing session data in cookies, the
database, or server memory, depending on the configuration.

Question 8. Which library can be used for generating PDF files in Django?

a) csv

b) json

c) reportlab(Correct)

d) requests

Explanation: The reportlab library can be used for generating PDF files in Django.

9. What is the purpose of MIME types in web development?

MALLIKARJUNA GD Page233 | 280


21CS62 Course Title : Fullstack Development

a) To handle user authentication

b) To generate RSS or Atom feeds

c) To specify the type of content being served(Correct)

d) To generate XML sitemaps

Explanation: MIME types are used to specify the type of content being served, such as HTML,
CSS, JavaScript, images, etc.

10. How do you set a MIME type for a file download in Django?

a) Using the content_type attribute of HttpResponse(Correct)

b) Using the set_content_type() method

c) Using the mime_type attribute of FileResponse

d) Using the set_mime_type() method

Explanation: You can set the MIME type for a file download in Django using the content_type
attribute of the HttpResponse class.

MALLIKARJUNA GD Page234 | 280


21CS62 Course Title : Fullstack Development

MODULE-5: JQUERY AND AJAX INTEGRATION IN DJANGO


Django, a popular web development framework, excels in building high-quality, scalable
web applications. One of its standout features is its seamless handling of asynchronous
requests, facilitated by Ajax (Asynchronous JavaScript and XML). Ajax allows web pages to
update asynchronously without the need for a page reload. In this blog post, we'll delve
into how to harness the power of Ajax within Django.

To integrate Ajax into Django, you'll first need to incorporate the necessary JavaScript
libraries into your project. Several options exist for this purpose, including jQuery, Vanilla
JavaScript, and ReactJS.

5.0 AJAX SOLUTION


Ajax (Asynchronous JavaScript and XML) is a web development technique that enables web
pages to update asynchronously without requiring a full page reload. This allows for a
smoother and more dynamic user experience by fetching and displaying data from the
server in the background, without disrupting the current page.

In Django, Ajax is commonly used to enhance interactivity and responsiveness in web


applications.

Client-Side Implementation (JavaScript):

• On the client-side (in the browser), JavaScript is used to make asynchronous


requests to the server.
• Typically, libraries like jQuery are used to simplify Ajax calls, although it's also
possible to use vanilla JavaScript or other libraries/frameworks like Axios or Fetch
API.
• JavaScript code is written to handle events, such as button clicks or form
submissions, and trigger Ajax requests to the Django server.

Server-Side Handling (Django Views):

• In Django, Ajax requests are handled by views, just like regular HTTP requests.
• Django views receive Ajax requests, process the data (if any), and return a
response.
• The response can be in various formats, such as JSON, XML, HTML, or plain text,
depending on the requirements of the application.

Communication between Client and Server:

• When a user interacts with a page (e.g., clicks a button), JavaScript code triggers
an Ajax request.
• The Ajax request is sent to a specific URL, typically mapped to a Django view.
• The Django view processes the request, performs any necessary operations (such
as database queries or computations), and generates a response.

MALLIKARJUNA GD Page235 | 280


21CS62 Course Title : Fullstack Development

• The response is sent back to the client, where it can be processed and used to
update the DOM (Document Object Model) dynamically, without a full page
reload.

Updating the DOM (Client-Side):

• Once the response is received from the server, JavaScript code on the client-side
processes it.
• Depending on the content of the response, the DOM may be updated to reflect
changes, display new data, or show error messages.
• This process typically involves manipulating HTML elements or updating the
content of specific elements on the page.

Error Handling and Validation:

• Error handling is an essential aspect of Ajax development. Both client-side and


server-side code should include mechanisms to handle errors gracefully.
• On the client-side, error callbacks can be used to handle situations such as network
errors or server-side failures.
• On the server-side, Django views should validate input data, handle exceptions,
and return appropriate error responses when necessary.

CSRF Protection:

• When using Ajax with Django for POST requests, it's crucial to protect against
Cross-Site Request Forgery (CSRF) attacks.
• Django provides built-in CSRF protection mechanisms, such as {% csrf_token %}
template tag or csrfmiddlewaretoken token in Ajax requests, to ensure the
security of your application.

By leveraging Ajax in Django, developers can create more dynamic and interactive web
applications, enhancing the overall user experience. However, it's essential to use Ajax
judiciously and consider factors such as performance, accessibility, and security while
implementing Ajax functionality.

Example:

let's create a simple example to demonstrate how to use Ajax in Django. In this example,
we'll create a Django application that allows users to submit a form asynchronously using
Ajax. When the form is submitted, the data will be sent to a Django view using Ajax, and
the server will respond with a success message.

Create a Django Project and App:

MALLIKARJUNA GD Page236 | 280


21CS62 Course Title : Fullstack Development

If you haven't already, create a new Django project and an app within it. Let's call the
project "ajax_example" and the app "ajax_app".

django-admin startproject ajax_example

cd ajax_example

python manage.py startapp ajax_app

Define URLs:

Configure the URL patterns to route requests to the appropriate views.

# ajax_example/urls.py

from django.urls import path

from ajax_app import views

urlpatterns = [

path('', views.index, name='index'),

path('ajax_submit/', views.ajax_submit, name='ajax_submit'),

Create Templates:

Create HTML templates for the index page and the success page.

<!-- ajax_app/templates/index.html -->

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Ajax Form Submission</title>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

</head>

<body>

<h1>Ajax Form Submission</h1>

MALLIKARJUNA GD Page237 | 280


21CS62 Course Title : Fullstack Development

<form id="ajax-form">

<label for="input-data">Enter Data:</label>

<input type="text" id="input-data" name="input_data">

<button type="submit">Submit</button>

</form>

<div id="result"></div>

<script src="{% static 'ajax_app/js/main.js' %}"></script>

</body>

</html>

Write JavaScript for Ajax:

Write JavaScript code to handle the form submission using Ajax.

// ajax_app/static/ajax_app/js/main.js

$(document).ready(function() {

$('#ajax-form').submit(function(event) {

event.preventDefault(); // Prevent the default form submission

var inputData = $('#input-data').val(); // Get the input value

$.ajax({

type: 'POST',

url: '/ajax_submit/', // URL to submit the form data

data: {'input_data': inputData}, // Form data to be submitted

success: function(response) {

$('#result').text(response.message); // Display the response message

},

error: function(xhr, errmsg, err) {

$('#result').text('Error occurred while submitting the form.'); // Display error


message

MALLIKARJUNA GD Page238 | 280


21CS62 Course Title : Fullstack Development

});

});

});

Define Views:

Define Django views to handle the form submission.

# ajax_app/views.py

from django.shortcuts import render

from django.http import JsonResponse

def index(request):

return render(request, 'ajax_app/index.html')

def ajax_submit(request):

if request.method == 'POST' and request.is_ajax():

input_data = request.POST.get('input_data')

# Process the input data (e.g., save to database)

response_data = {'message': 'Form submitted successfully!'}

return JsonResponse(response_data)

else:

return JsonResponse({'error': 'Invalid request'})

Run the Server:

Finally, run the Django development server to see the application in action.

python manage.py runserver

Now, when you navigate to the homepage (http://127.0.0.1:8000/), you should see a form
where you can enter data. When you submit the form, the data will be sent asynchronously
using Ajax to the Django server. The server will respond with a success message, which will
be displayed on the page without a full page reload.

5.1 JAVASCRIPT
JavaScript is a versatile programming language commonly used for web development. It
allows developers to add interactivity, dynamic behavior, and functionality to web pages.

MALLIKARJUNA GD Page239 | 280


21CS62 Course Title : Fullstack Development

Client-Side Scripting: JavaScript primarily runs on the client-side (in the user's web
browser), unlike server-side languages like Python (used in Django). This means JavaScript
code is executed on the user's device, allowing for real-time interaction without needing
to communicate with the server for every action.

Dynamic Content: JavaScript enables the manipulation of HTML and CSS, allowing
developers to dynamically update the content and styling of web pages based on user
interactions or other events. This includes actions like showing/hiding elements, changing
text or images, and animating elements.

Event Handling: JavaScript allows developers to respond to various events triggered by


user interactions, such as mouse clicks, keyboard inputs, form submissions, and page
load/completion. Event handlers can be attached to HTML elements to execute JavaScript
code when the event occurs.

DOM Manipulation: The Document Object Model (DOM) is a programming interface that
represents the structure of an HTML document as a tree of nodes. JavaScript can interact
with and manipulate the DOM, enabling the addition, removal, or modification of elements
and their attributes on the fly.

Asynchronous Programming: JavaScript supports asynchronous programming, allowing


tasks to be executed concurrently without blocking the main execution thread. This is
crucial for tasks such as making Ajax requests, handling timeouts/intervals, and processing
data in the background.

Libraries and Frameworks: JavaScript has a vast ecosystem of libraries and frameworks
that streamline web development tasks and provide additional functionality. Popular
libraries like jQuery simplify DOM manipulation and Ajax requests, while frameworks like
React, Angular, and Vue.js offer more structured approaches to building complex web
applications.

Browser Compatibility: JavaScript code can run on most modern web browsers, including
Chrome, Firefox, Safari, and Edge. However, developers need to consider browser
compatibility and may need to use polyfills or feature detection to ensure consistent
behavior across different browsers.

Security Considerations: As JavaScript executes on the client-side, it's important to


consider security risks such as Cross-Site Scripting (XSS) attacks, where malicious scripts
are injected into web pages. Proper input validation, output encoding, and secure coding
practices are essential for mitigating these risks.

Overall, JavaScript is a fundamental technology for web development, empowering


developers to create interactive and engaging web applications that enhance the user
experience

MALLIKARJUNA GD Page240 | 280


21CS62 Course Title : Fullstack Development

Example:

<!DOCTYPE html>

<html>

<head>

<title>JavaScript Example</title>

</head>

<body>

<h1 id="heading">Hello, World!</h1>

<button id="change-text">Change Text</button>

<script>

// JavaScript code to handle button click event and modify the heading text

document.getElementById("change-text").addEventListener("click", function() {

var heading = document.getElementById("heading");

heading.textContent = "Text Changed!";

heading.style.color = "red";

});

</script>

</body>

</html>

In this example:

• HTML defines a heading and a button.


• JavaScript code adds an event listener to the button, which changes the heading
text and color when clicked.
• The textContent property is used to modify the text content of the heading
element.
• The style property is used to modify the CSS style of the heading element.

Quickglance:

Introduction to JavaScript

• JavaScript is a scripting language primarily used for client-side web development.

MALLIKARJUNA GD Page241 | 280


21CS62 Course Title : Fullstack Development

• It was developed by Brendan Eich at Netscape Communications in 1995.


• JavaScript is used to add interactivity and dynamic behavior to web pages.

Basic Syntax and Data Types

Variables: var, let, const are used to declare variables.

var age = 30;

let name = "John";

const PI = 3.14;

Data types: strings, numbers, booleans, null, undefined.

var name = "John";

var age = 30;

var isStudent = true;

var car = null;

var test;

Control Structures

Conditional statements: if, else if, else.

var age = 18;

if (age >= 18) {

console.log("You are an adult.");

MALLIKARJUNA GD Page242 | 280


21CS62 Course Title : Fullstack Development

} else {

console.log("You are a minor.");

Loops: for, while, do-while.

for (var i = 0; i < 5; i++) {

console.log(i);

Functions

Functions are blocks of reusable code.

function greet(name) {

return "Hello, " + name + "!";

console.log(greet("John"));

Arrow functions:

var add = (a, b) => a + b;

console.log(add(2, 3)); // Output: 5

Arrays and Objects

Arrays: Ordered collections of values.

var fruits = ["apple", "banana", "orange"];

console.log(fruits[0]); // Output: apple

Objects: Key-value pairs.

var person = { name: "John", age: 30 };

console.log(person.name); // Output: John

DOM Manipulation

DOM represents the structure of HTML documents.

document.getElementById("myButton").addEventListener("click", function() {

alert("Button clicked!");

MALLIKARJUNA GD Page243 | 280


21CS62 Course Title : Fullstack Development

});

Introduction to Asynchronous JavaScript

setTimeout: Executes a function after a specified time.

setTimeout(function() {

console.log("Delayed message.");

}, 2000); // Execute after 2 seconds

Error Handling and Debugging

try-catch blocks: Handle errors gracefully.

try {

// Code that may throw an error

} catch (error) {

// Handle the error

ES6 Features

Template literals: Allows embedding expressions in strings.

var name = "John";

console.log(`Hello, ${name}!`);

Asynchronous Programming

Promises: Handle asynchronous operations.

var promise = new Promise(function(resolve, reject) {

setTimeout(function() {

resolve("Data fetched successfully.");

}, 2000);

});

promise.then(function(data) {

console.log(data);

});

MALLIKARJUNA GD Page244 | 280


21CS62 Course Title : Fullstack Development

AJAX and Fetch API

Fetch API: Fetch data from a server asynchronously.

fetch('https://api.example.com/data')

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.log(error));

Local Storage

Store data locally in the browser.

localStorage.setItem("name", "John");

var name = localStorage.getItem("name");

console.log(name); // Output: John

Advanced DOM Manipulation

Event delegation: Handling events on dynamically created elements.

document.addEventListener("click", function(event) {

if (event.target.matches("button")) {

console.log("Button clicked.");

});

Object-Oriented JavaScript

Prototypes and inheritance: Define methods shared among objects.

function Person(name) {

this.name = name;

Person.prototype.greet = function() {

return "Hello, " + this.name + "!";

};

var john = new Person("John");

MALLIKARJUNA GD Page245 | 280


21CS62 Course Title : Fullstack Development

console.log(john.greet());

Module Systems

ES6 modules: Organize and share code across files.

// math.js

export function add(a, b) {

return a + b;

// app.js

import { add } from './math.js';

console.log(add(2, 3)); // Output: 5

Web APIs

Geolocation API: Retrieve the user's location.

navigator.geolocation.getCurrentPosition(function(position) {

console.log("Latitude:", position.coords.latitude);

console.log("Longitude:", position.coords.longitude);

});

Testing and Debugging

Jest: Unit testing framework for JavaScript.

function add(a, b) {

return a + b;

test('adds 1 + 2 to equal 3', () => {

expect(add(1, 2)).toBe(3);

});

Performance Optimization

• Minification: Reduce file size by removing unnecessary characters.


• Code splitting: Split code into smaller chunks to improve loading times.

MALLIKARJUNA GD Page246 | 280


21CS62 Course Title : Fullstack Development

Security Best Practices

• Cross-Site Scripting (XSS) prevention: Sanitize user input to prevent script


injection.
• Content Security Policy (CSP): Define policies to mitigate XSS attacks.

5.2 XML
In Django, XML (eXtensible Markup Language) can be used for various purposes, such as
data interchange, configuration files, or representing structured data. While JSON
(JavaScript Object Notation) is more commonly used for data interchange in web
applications due to its lightweight and easy-to-read format, Django does provide facilities
for handling XML data when needed.

XML Parsing and Generation:

Django provides modules for parsing and generating XML data. The xml.etree.ElementTree
module in Python's standard library is often used for XML parsing and generation in Django
projects.

Integration with Django Models:

XML data can be integrated with Django models for data import/export or synchronization
with external systems. You can use Django's ORM (Object-Relational Mapping) to query
database records and serialize them into XML format.

XML Rendering in Views:

Django views can render XML responses using Django's HttpResponse class. This allows
you to serve XML data to clients making requests to your Django application.

Django Rest Framework (DRF):

If you're building a RESTful API with Django using Django Rest Framework (DRF), you have
the flexibility to serialize data into XML format alongside JSON. DRF's serializers support
XML rendering and parsing out of the box.

XML Configuration Files:

Django projects often use XML files for configuration purposes, such as defining URL
patterns in the urls.py file or configuring settings for third-party apps.

Third-party Libraries:

While Django provides basic support for handling XML data, you can also leverage third-
party libraries for more advanced XML processing tasks. Libraries like lxml offer powerful
XML parsing and manipulation capabilities.

XML-RPC and SOAP:

MALLIKARJUNA GD Page247 | 280


21CS62 Course Title : Fullstack Development

Django can be used to implement XML-RPC (Remote Procedure Call) and SOAP (Simple
Object Access Protocol) APIs. These protocols use XML for data exchange between clients
and servers.

XML Schema Validation:

Django does not natively support XML Schema validation out of the box, but you can
integrate third-party XML schema validation libraries into your Django project if needed.

Overall, while JSON is more prevalent in web development, Django provides sufficient
support for handling XML data when required. Whether it's integrating XML with Django
models, rendering XML responses in views, or processing XML data in APIs, Django offers
the flexibility to work with XML effectively within its framework.

EXAMPLE

Let's create a simple example demonstrating how to integrate XML handling in a Django
project. In this example, we'll create a Django app that reads data from a database and
serializes it into XML format. We'll then create a view that serves this XML data as a
response.

Assuming you have a Django project set up with a Django app named xml_example, here's
how you can implement it:

Model Definition:

Define a Django model in models.py representing the data you want to serialize.

# xml_example/models.py

from django.db import models

class Book(models.Model):

title = models.CharField(max_length=100)

author = models.CharField(max_length=100)

published_date = models.DateField()

def __str__(self):

return self.title

View Implementation:

Create a Django view in views.py that fetches data from the database and serializes it
into XML format.

# xml_example/views.py

MALLIKARJUNA GD Page248 | 280


21CS62 Course Title : Fullstack Development

from django.http import HttpResponse

from django.core.serializers import serialize

from .models import Book

def books_xml(request):

books = Book.objects.all()

xml_data = serialize('xml', books)

return HttpResponse(xml_data, content_type='application/xml')

URL Configuration:

Map the view to a URL in urls.py.

# xml_example/urls.py

from django.urls import path

from .views import books_xml

urlpatterns = [

path('books/xml/', books_xml, name='books_xml'),

Database Population:

Populate the database with some sample data using Django's admin interface or Django
shell.

Accessing the XML Data:

Start the Django development server (python manage.py runserver) and navigate to
http://localhost:8000/books/xml/ to access the XML data representing the books stored
in the database.

This example demonstrates how to serialize Django model data into XML format and
serve it as a response using a Django view. You can extend this example by customizing
the XML serialization, adding more fields to the model, or incorporating XML parsing for
handling XML data received from clients.

5.3 HTTPREQUEST AND RESPONSE


HTTP (Hypertext Transfer Protocol) requests and responses are the foundation of
communication between clients (such as web browsers) and servers. In Django,

MALLIKARJUNA GD Page249 | 280


21CS62 Course Title : Fullstack Development

HttpRequest and HttpResponse are classes used to handle incoming requests from clients
and send responses back to them, respectively.

Let's explore HttpRequest and HttpResponse in Django:

HttpRequest:

HttpRequest represents an incoming HTTP request from a client to the Django server.

It contains metadata about the request, such as headers, request method, URL, query
parameters, POST data, etc.

Attributes:

• method: HTTP method used for the request (GET, POST, PUT, DELETE, etc.).
• path: Path portion of the requested URL.
• GET: Dictionary-like object containing query parameters from the URL.
• POST: Dictionary-like object containing POST data sent in the request body.
• META: Dictionary containing metadata about the request (headers, IP address,
user agent, etc.).

Usage:

HttpRequest objects are passed as the first argument to Django view functions.

Views access request data through attributes like GET, POST, and META.

HttpResponse:

HttpResponse represents an HTTP response sent from the Django server to the client.

It contains the response content, status code, and headers.

Attributes/Methods:

• content: Content of the response (HTML, JSON, XML, etc.).


• status_code: HTTP status code of the response (200 for OK, 404 for Not Found,
etc.).
• set_cookie(): Method to set cookies in the response.
• delete_cookie(): Method to delete cookies from the response.
• headers: Dictionary-like object representing response headers.

Usage:

Django views return HttpResponse objects to send responses back to clients.

HttpResponse objects can be customized with response content, status code, and headers.

MALLIKARJUNA GD Page250 | 280


21CS62 Course Title : Fullstack Development

Example:

let's create a simple Django project from scratch and implement a view that handles an
HTTP request and sends back an HTTP response.

First, ensure you have Django installed. If not, you can install it via pip:

pip install django

Now, let's create a new Django project and app:

django-admin startproject myproject

cd myproject

python manage.py startapp myapp

Next, let's define a view that handles an HTTP request and sends back a simple HTTP
response.

Open myapp/views.py and add the following code:

from django.http import HttpResponse

def hello_world(request):

return HttpResponse("Hello, World!")

This view function, hello_world, takes an HttpRequest object as an argument and returns
an HttpResponse object with the content "Hello, World!".

Now, we need to define a URL pattern that maps to this view.

Open myproject/urls.py and add the following code:

from django.urls import path

from myapp.views import hello_world

urlpatterns = [

path('hello/', hello_world, name='hello_world'),

This maps the URL /hello/ to the hello_world view function we defined earlier.

Finally, let's run the Django development server and test our view.

Run the following command:

python manage.py runserver

MALLIKARJUNA GD Page251 | 280


21CS62 Course Title : Fullstack Development

Now, open your web browser and navigate to http://127.0.0.1:8000/hello/. You should
see the text "Hello, World!" displayed in the browser, indicating that our view is
successfully handling the HTTP request and sending back the HTTP response.

5.4 HTML
let's provide a quick glance at how HTML is used in conjunction with Django to create
dynamic web pages:

Template System:

Django comes with a powerful template engine that allows you to build HTML templates
with placeholders for dynamic data.

HTML Template Files:

HTML templates in Django are regular HTML files with additional template tags and filters
provided by the Django template engine.

Template Tags:

Template tags are enclosed in {% %} and allow you to add logic and control flow to your
templates. For example, {% if %}, {% for %}, {% include %}, etc.

Template Filters:

Template filters are enclosed in {{ }} and allow you to modify the output of template
variables. For example, {{ variable|default:"No data" }}, {{ variable|date:"Y-m-d" }}, etc.

Context Data:

Context data is passed from views to templates and contains dynamic data that will be
rendered in the HTML. Views render templates with context data using the render()
function.

Static Files:

Static files such as CSS, JavaScript, images, etc., can be included in Django templates using
the {% static %} template tag. These files are served by Django's static file server during
development.

Forms:

Django provides form handling functionalities that generate HTML form elements in
templates. Forms can be rendered manually or by using Django's form rendering helpers.

URLs and Links:

MALLIKARJUNA GD Page252 | 280


21CS62 Course Title : Fullstack Development

Django's template engine provides the {% url %} template tag to generate URLs for views.
This allows you to create links dynamically in your HTML templates.

Inheritance:

Django templates support template inheritance, allowing you to define a base template
with common layout and structure, and then extend it in child templates to override
specific blocks.

HTML Escaping:

Django automatically escapes HTML special characters in template variables to prevent


XSS (Cross-Site Scripting) attacks. Use the safe filter to mark a string as safe HTML if
necessary.

Example:

Let's create a simple example to illustrate how HTML is used with Django templates:

Template File (myapp/templates/index.html):

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>{{ title }}</title>

</head>

<body>

<h1>Welcome to {{ title }}</h1>

<ul>

{% for item in items %}

<li>{{ item }}</li>

{% endfor %}

</ul>

<p>Today's date is {{ current_date|date:"F d, Y" }}</p>

MALLIKARJUNA GD Page253 | 280


21CS62 Course Title : Fullstack Development

<a href="{% url 'about_page' %}">About</a>

<img src="{% static 'images/logo.png' %}" alt="Logo">

</body>

</html>

View Function:

from django.shortcuts import render

from datetime import datetime

def index(request):

context = {

'title': 'My Django App',

'items': ['Item 1', 'Item 2', 'Item 3'],

'current_date': datetime.now(),

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

URL Configuration (urls.py):

from django.urls import path

from myapp.views import index

urlpatterns = [

path('', index, name='index'),

Static Files:

Place static files (e.g., logo.png) in the myapp/static/ directory.

Link to About Page (myapp/templates/about.html):

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

MALLIKARJUNA GD Page254 | 280


21CS62 Course Title : Fullstack Development

<title>About Us</title>

</head>

<body>

<h1>About Us</h1>

<p>This is the about page of our Django app.</p>

<a href="{% url 'index' %}">Back to Home</a>

</body>

</html>

In this example, we have a base template index.html that renders dynamic data such as
the title, a list of items, the current date, and a link to the about page. We use template
tags like {% for %}, {% url %}, and {% static %} to generate dynamic content and links. The
view function retrieves data and renders the template with the context data.

5.5 CSS
Cascading Style Sheets (CSS):

• CSS is a stylesheet language used to style the appearance of HTML elements on


web pages.
• It allows web developers to control the layout, colors, fonts, and other visual
aspects of a website.

Key Concepts:

• Selectors: Used to target HTML elements for styling.


• Properties: Define the visual characteristics of the selected elements.
• Values: Specify the desired settings for the properties.

Example:

/* CSS code */

h1 {

color: blue;

font-size: 24px;

text-align: center;

<!-- HTML code -->

MALLIKARJUNA GD Page255 | 280


21CS62 Course Title : Fullstack Development

<h1>This is a Heading</h1>

CSS Selectors and Box Model

Selectors:

• Element Selector: Targets HTML elements by their tag name.


• Class Selector: Targets elements with a specific class attribute.
• ID Selector: Targets a single element with a unique ID attribute.
• Descendant Selector: Targets elements that are descendants of a specified
parent.
• Pseudo-classes: Targets elements based on their state or position.

Box Model:

• Content: The actual content of the element.


• Padding: Space between the content and the border.
• Border: The border surrounding the padding.
• Margin: Space outside the border, separating the element from other elements.

Example:

/* CSS code */

.box {

width: 200px;

height: 100px;

padding: 20px;

border: 2px solid black;

margin: 10px;

<!-- HTML code -->

<div class="box">Box Content</div>

CSS Flexbox and Grid Layout

Flexbox:

• Provides a flexible way to layout elements within a container.


• Allows for dynamic alignment and distribution of space among items.

MALLIKARJUNA GD Page256 | 280


21CS62 Course Title : Fullstack Development

Grid Layout:

• Defines a two-dimensional grid system for layout design.


• Allows precise positioning and alignment of elements in rows and columns.

Example:

/* CSS code */

.container {

display: flex;

justify-content: center;

align-items: center;

<!-- HTML code -->

<div class="container">

<div>Item 1</div>

<div>Item 2</div>

<div>Item 3</div>

</div>

CSS Animations and Transitions

Animations:

• Allows for the creation of dynamic, interactive effects on web pages.


• Keyframes define the intermediate steps of the animation.

Transitions:

• Smoothly animates the transition of an element's property from one state to


another.
• Transition properties include duration, timing function, delay, and property to
transition.

Example:

/* CSS code */

@keyframes slide {

MALLIKARJUNA GD Page257 | 280


21CS62 Course Title : Fullstack Development

0% { transform: translateX(0); }

100% { transform: translateX(100px); }

.box {

width: 100px;

height: 100px;

background-color: blue;

animation: slide 2s infinite alternate;

<!-- HTML code -->

<div class="box"></div>

Responsive Design and Media Queries

Responsive Design:

• Ensures that web pages render well on various devices and screen sizes.
• Utilizes flexible grids, images, and CSS media queries.

Media Queries:

Allows for the adaptation of styles based on the characteristics of the device, such as
screen width, height, and orientation.

Example:

/* CSS code */

@media screen and (max-width: 600px) {

.container {

flex-direction: column;

<!-- HTML code -->

<div class="container">

MALLIKARJUNA GD Page258 | 280


21CS62 Course Title : Fullstack Development

<div>Item 1</div>

<div>Item 2</div>

<div>Item 3</div>

</div>

Example: simple example of a phone directory web application using Django for the
backend and HTML/CSS/JavaScript for the frontend.

Let's start with the Django backend:

First, make sure you have Django installed. You can install it via pip:

pip install django

Create a new Django project:

django-admin startproject phone_directory

Create a Django app within the project:

cd phone_directory

django-admin startapp directory

Define your model in directory/models.py:

from django.db import models

class Contact(models.Model):

name = models.CharField(max_length=100)

phone = models.CharField(max_length=20)

def __str__(self):

return self.name

Register your model in directory/admin.py:

from django.contrib import admin

from .models import Contact

admin.site.register(Contact)

Create a view in directory/views.py:

from django.shortcuts import render

MALLIKARJUNA GD Page259 | 280


21CS62 Course Title : Fullstack Development

from .models import Contact

def index(request):

contacts = Contact.objects.all()

return render(request, 'directory/index.html', {'contacts': contacts})

Create a template index.html in directory/templates/directory:

html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Phone Directory</title>

<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

</head>

<body>

<div class="container">

<h1>Phone Directory</h1>

<ul>

{% for contact in contacts %}

<li>{{ contact.name }} - {{ contact.phone }}</li>

{% endfor %}

</ul>

</div>

</body>

</html>

Now, let's move to the frontend part:

MALLIKARJUNA GD Page260 | 280


21CS62 Course Title : Fullstack Development

Create a CSS file styles.css in phone_directory/static/css:

css

/* styles.css */

body {

font-family: Arial, sans-serif;

background-color: #f4f4f4;

margin: 0;

padding: 0;

.container {

max-width: 800px;

margin: 20px auto;

padding: 20px;

background-color: #fff;

border-radius: 5px;

box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

h1 {

color: #333;

ul {

list-style-type: none;

padding: 0;

MALLIKARJUNA GD Page261 | 280


21CS62 Course Title : Fullstack Development

li {

margin-bottom: 10px;

Link the CSS file in your HTML template:

html

<link rel="stylesheet" href="{% static 'css/styles.css' %}">

Now, you can run your Django server:

Python manage.py runserver

And you should be able to see your phone directory application running at
http://127.0.0.1:8000/. You can then add more features like adding new contacts, editing
existing contacts, etc., based on your requirements.

5.6 JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for
humans to read and write and easy for machines to parse and generate. It is based on a
subset of the JavaScript programming language, but it's language-independent, meaning
it can be used with most programming languages.

JSON is commonly used for transmitting data between a server and a web application as
an alternative to XML. It's widely used in web development for APIs (Application
Programming Interfaces) because it's simple, easy to understand, and lightweight.

JSON data is represented as key-value pairs, similar to Python dictionaries or JavaScript


objects. The keys are strings, and the values can be strings, numbers, arrays, objects,
booleans, or null.

Here's an example of JSON data representing information about a person:

"name": "Mallikarjuna",

"age": 30,

"is_student": false,

"address": {

"street": "123 Main St",

MALLIKARJUNA GD Page262 | 280


21CS62 Course Title : Fullstack Development

"city": "Mysuru",

"state": "CA"

},

"hobbies": ["reading", "hiking", "coding"]

In this example:

• "name", "age", and "is_student" are key-value pairs with string keys and string or
boolean values.
• "address" is a key-value pair where the value is another object containing keys
"street", "city", and "state".
• "hobbies" is a key-value pair where the value is an array containing strings.

JSON data can be parsed and converted into native data types in most programming
languages, making it easy to work with in a variety of contexts.

simple example:

Let's say we want to create a simple JSON API for managing contacts.

Model Setup:

# models.py

from django.db import models

class Contact(models.Model):

name = models.CharField(max_length=100)

phone = models.CharField(max_length=20)

def to_json(self):

return {'name': self.name, 'phone': self.phone}

Serializer Creation (Optional):

# serializers.py

from rest_framework import serializers

from .models import Contact

MALLIKARJUNA GD Page263 | 280


21CS62 Course Title : Fullstack Development

class ContactSerializer(serializers.ModelSerializer):

class Meta:

model = Contact

fields = ['name', 'phone']

Views:

# views.py

from django.http import JsonResponse

from .models import Contact

def get_contacts(request):

contacts = Contact.objects.all()

data = [contact.to_json() for contact in contacts]

return JsonResponse(data, safe=False)

URL Configuration:

# urls.py

from django.urls import path

from .views import get_contacts

urlpatterns = [

path('contacts/', get_contacts, name='get_contacts'),

With this setup, when you visit http://127.0.0.1:8000/contacts/, you'll receive a JSON
response containing all the contacts in the database.

Make sure to install Django Rest Framework (pip install djangorestframework) if you
choose to use serializers from it. Also, don't forget to include the app in your Django
project's INSTALLED_APPS setting and set up your database.

5.7 USING JQUERY UI AUTOCOMPLETE IN DJANGO


Query is a fast, small, and feature-rich JavaScript library. It simplifies various tasks like
HTML document traversal and manipulation, event handling, animation, and Ajax
interactions for web development. jQuery was created by John Resig in 2006 and has since
become one of the most popular JavaScript libraries used by developers worldwide.

MALLIKARJUNA GD Page264 | 280


21CS62 Course Title : Fullstack Development

Some key features and benefits of jQuery:

• DOM Manipulation: jQuery provides an easy-to-use API for selecting and manipulating
HTML elements in the Document Object Model (DOM). With jQuery, you can easily
traverse the DOM tree, modify element attributes and content, and add or remove
elements from the page.
• Event Handling: jQuery simplifies event handling by providing methods for attaching
event listeners to HTML elements. You can handle user interactions such as clicks,
mouse movements, keyboard inputs, and more with ease.
• AJAX Support: jQuery simplifies asynchronous HTTP requests (Ajax) by providing a set
of methods for making requests to the server and handling server responses. This
allows you to load data from the server without refreshing the entire web page, leading
to a more responsive user experience.
• Animation Effects: jQuery includes built-in animation effects and methods for creating
custom animations. You can animate CSS properties, show/hide elements with various
effects, and create complex animations with ease.
• Cross-browser Compatibility: jQuery abstracts away many browser inconsistencies and
provides a unified interface that works across different web browsers. This helps
developers write code that behaves consistently across various browser environments.
• Extensibility: jQuery is highly extensible, allowing developers to create plugins to
extend its functionality further. There is a vast ecosystem of jQuery plugins available
for various purposes, ranging from UI components to complex data visualization tools.

Overall, jQuery simplifies JavaScript development and makes it easier to create dynamic,
interactive, and responsive web applications. However, with the advancement of modern
web technologies and improvements in browser APIs, some developers prefer using native
JavaScript or modern frameworks/libraries like React, Vue.js, or Angular for new projects

Example:

let's create a simple Django project from scratch and integrate jQuery step by step.

Create a Django Project:

django-admin startproject myproject

cd myproject

Create a Django App:

python manage.py startapp myapp

Define a View:

MALLIKARJUNA GD Page265 | 280


21CS62 Course Title : Fullstack Development

In myapp/views.py, define a simple view that renders a template.

from django.shortcuts import render

def index(request):

return render(request, 'myapp/index.html')

Create a Template:

Create a directory named templates in the myapp directory. Inside templates, create a file
named index.html.

html

<!-- myapp/templates/index.html -->

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Django with jQuery</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>

$(document).ready(function() {

// Example: Alert message on button click

$('#myButton').click(function() {

alert('Button clicked!');

});

});

</script>

</head>

<body>

<button id="myButton">Click me</button>

MALLIKARJUNA GD Page266 | 280


21CS62 Course Title : Fullstack Development

</body>

</html>

Define URLs:

In myproject/urls.py, define a URL pattern to map to the view.

from django.urls import path

from myapp.views import index

urlpatterns = [

path('', index, name='index'),

Run the Server:

python manage.py runserver

Visit http://127.0.0.1:8000/ in your browser, and you should see a button. When you click
the button, it should display an alert message, demonstrating the use of jQuery.

This setup demonstrates the integration of jQuery with Django from scratch. You can
further expand the project by adding more views, templates, and jQuery functionality as
needed for your application.

5.8 PRACTICES
5.12.1 Develop a registration page for student enrolment as done in Module 2 but without page
refresh using AJAX.
let's develop a registration page for student enrollment using Django and AJAX. We'll
create a form where students can input their information, and upon submission, the data
will be sent to the server using AJAX without refreshing the page. Here's a step-by-step
guide:

Create a Django Project:

django-admin startproject enrollment_project

cd enrollment_project

Create a Django App:

python manage.py startapp enrollment

Define Model:

MALLIKARJUNA GD Page267 | 280


21CS62 Course Title : Fullstack Development

In enrollment/models.py, define a model for Student with fields like name, email, and
course.

from django.db import models

class Student(models.Model):

name = models.CharField(max_length=100)

email = models.EmailField(max_length=100)

course = models.CharField(max_length=100)

def __str__(self):

return self.name

Create a Form:

In enrollment/forms.py, create a Django form for student registration.

from django import forms

from .models import Student

class StudentForm(forms.ModelForm):

class Meta:

model = Student

fields = ['name', 'email', 'course']

Create a View:

In enrollment/views.py, define a view to handle the registration form.

from django.shortcuts import render

from django.http import JsonResponse

from .forms import StudentForm

def register_student(request):

if request.method == 'POST':

form = StudentForm(request.POST)

if form.is_valid():

form.save()

MALLIKARJUNA GD Page268 | 280


21CS62 Course Title : Fullstack Development

return JsonResponse({'success': True})

else:

return JsonResponse({'success': False, 'errors': form.errors})

else:

form = StudentForm()

return render(request, 'enrollment/register.html', {'form': form})

Create a Template:

In enrollment/templates/enrollment/register.html, create an HTML template for the


registration form.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Student Enrollment</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>

$(document).ready(function() {

$('#registrationForm').submit(function(event) {

event.preventDefault();

$.ajax({

type: 'POST',

url: '{% url "register_student" %}',

data: $(this).serialize(),

success: function(response) {

if (response.success) {

alert('Registration successful!');

MALLIKARJUNA GD Page269 | 280


21CS62 Course Title : Fullstack Development

} else {

alert('Registration failed. Please check your inputs.');

},

error: function(xhr, status, error) {

console.error(error);

});

});

});

</script>

</head>

<body>

<h1>Student Enrollment</h1>

<form id="registrationForm">

{% csrf_token %}

{{ form.as_p }}

<button type="submit">Register</button>

</form>

</body>

</html>

Define URLs:

In enrollment/urls.py, define a URL pattern to map to the view.

from django.urls import path

from .views import register_student

urlpatterns = [

MALLIKARJUNA GD Page270 | 280


21CS62 Course Title : Fullstack Development

path('register/', register_student, name='register_student'),

Update Project URLs:

In enrollment_project/urls.py, include the URLs of the enrollment app.

from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path('admin/', admin.site.urls),

path('enrollment/', include('enrollment.urls')),

Run the Server:

python manage.py runserver

Visit http://127.0.0.1:8000/enrollment/register/ in your browser, fill out the registration


form, and submit it. You should see a success message if the registration is successful or
an error message if there are validation errors. The page won't refresh upon submission,
due to the AJAX request.

5.12.2 Develop a search application in Django using AJAX that displays courses enrolled by a
student being searched
we'll create a basic Django project with a single app that allows users to search for students
and display the courses enrolled by the selected student using AJAX.

The steps to create this application:

• Setup Django Project: Create a new Django project.


• Create Django App: Create a new Django app for managing students and courses.
• Define Models: Define models for Student and Course.
• Create Views: Create views for rendering search page and handling AJAX requests.
• Define URLs: Define URL patterns for the views.
• Create Templates: Create HTML templates for search page and AJAX response.
• Write JavaScript: Write JavaScript code to handle AJAX requests and update the
page dynamically.

Let's start by setting up the Django project and app.

MALLIKARJUNA GD Page271 | 280


21CS62 Course Title : Fullstack Development

# Create a new Django project

django-admin startproject search_project

# Navigate to the project directory

cd search_project

# Create a new Django app

python manage.py startapp search_app

Now, let's define the models in search_app/models.py:

from django.db import models

class Student(models.Model):

name = models.CharField(max_length=100)

def __str__(self):

return self.name

class Course(models.Model):

name = models.CharField(max_length=100)

student = models.ForeignKey(Student, on_delete=models.CASCADE)

def __str__(self):

return self.name

Next, we'll create views in search_app/views.py:

from django.shortcuts import render

from django.http import JsonResponse

from .models import Student, Course

def search(request):

return render(request, 'search.html')

def search_student(request):

if request.method == 'GET' and 'query' in request.GET:

query = request.GET['query']

MALLIKARJUNA GD Page272 | 280


21CS62 Course Title : Fullstack Development

students = Student.objects.filter(name__icontains=query)

data = [{'id': student.id, 'name': student.name} for student in students]

return JsonResponse(data, safe=False)

else:

return JsonResponse({'error': 'Invalid request'})

def get_courses(request):

if request.method == 'GET' and 'student_id' in request.GET:

student_id = request.GET['student_id']

courses = Course.objects.filter(student_id=student_id)

data = [{'name': course.name} for course in courses]

return JsonResponse(data, safe=False)

else:

return JsonResponse({'error': 'Invalid request'})

Now, define the URLs in search_project/urls.py:

from django.urls import path

from search_app import views

urlpatterns = [

path('', views.search, name='search'),

path('search_student/', views.search_student, name='search_student'),

path('get_courses/', views.get_courses, name='get_courses'),

Create templates for the search page and AJAX response in


search_app/templates/search.html:

<!DOCTYPE html>

<html lang="en">

<head>

MALLIKARJUNA GD Page273 | 280


21CS62 Course Title : Fullstack Development

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Search</title>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

</head>

<body>

<h1>Search Students</h1>

<input type="text" id="searchInput" placeholder="Enter student name...">

<ul id="studentList"></ul>

<div id="courseList"></div>

<script>

$(document).ready(function(){

$('#searchInput').on('input', function(){

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

$.ajax({

url: '/search_student/',

data: {'query': query},

dataType: 'json',

success: function(data){

$('#studentList').empty();

data.forEach(function(student){

$('#studentList').append('<li data-student-
id="'+student.id+'">'+student.name+'</li>');

});

MALLIKARJUNA GD Page274 | 280


21CS62 Course Title : Fullstack Development

});

});

$('#studentList').on('click', 'li', function(){

var studentId = $(this).data('student-id');

$.ajax({

url: '/get_courses/',

data: {'student_id': studentId},

dataType: 'json',

success: function(data){

$('#courseList').empty();

data.forEach(function(course){

$('#courseList').append('<p>'+course.name+'</p>');

});

});

});

});

</script>

</body>

</html>

Finally, run the Django development server:

python manage.py runserver

MALLIKARJUNA GD Page275 | 280


21CS62 Course Title : Fullstack Development

Now you can open your browser and navigate to http://127.0.0.1:8000/ to access the
search page. As you type in the search input, it will display matching students dynamically.
When you click on a student, it will fetch and display the courses enrolled by that student

5.9 IMPORTANT NOTE


• What is AJAX, and how does it enhance the user experience in web applications?
• How can you integrate AJAX into Django projects?
• Explain the difference between synchronous and asynchronous JavaScript.
• What are the different types of HTTP requests supported by AJAX, and how are
they used?
• How do you handle AJAX requests and responses in Django views?
• What is the purpose of using JavaScript frameworks like jQuery in Django projects?
• Explain the concept of event handling in JavaScript and how it applies to AJAX
interactions.
• How do you serialize Django model data to JSON format for AJAX responses?
• What are the advantages and disadvantages of using XML compared to JSON in
AJAX requests?
• How can you implement server-side validation for AJAX requests in Django?
• Describe the process of implementing real-time updates using AJAX in Django.
• How do you prevent cross-site request forgery (CSRF) attacks when using AJAX in
Django?
• Explain the role of jQuery plugins in enhancing AJAX functionality in Django
applications.
• What are the best practices for optimizing performance when using AJAX in
Django?
• How do you troubleshoot common issues encountered when working with jQuery
and AJAX in Django projects?

5.10 MCQ
Question 1: What does AJAX stand for?

A) Asynchronous JavaScript and XML(correct)

B) Asynchronous JavaScript and XHTML

C) Asynchronous JSON and XML

D) Asynchronous JavaScript and HTML

Explanation: AJAX allows web pages to be updated asynchronously by exchanging small


amounts of data with the server behind the scenes. While it originally stood for Asynchronous
JavaScript and XML, it's commonly used with JSON and other data formats as well.

MALLIKARJUNA GD Page276 | 280


21CS62 Course Title : Fullstack Development

Question 2:Which HTTP request method is typically used for retrieving data from the server
in AJAX?

A) GET(correct)

B) POST

C) PUT

D) DELETE

Explanation: The GET method is commonly used in AJAX for retrieving data from the server
without altering the server's state.

Question 3: What is the purpose of the jQuery library in AJAX development?

A) To simplify DOM manipulation (correct)

B) To handle HTTP requests asynchronously

C) To provide cross-browser compatibility

D) To enhance server-side processing

Explanation: jQuery simplifies JavaScript coding by providing easy-to-use methods for DOM
manipulation, event handling, and AJAX interactions.

Question 4: Which jQuery method is commonly used to make AJAX requests?

A) $.ajax() (correct)

B) $.get()

C) $.post()

D) $.load()

Explanation: The $.ajax() method is a versatile method for making AJAX requests in jQuery,
allowing for customization of various options such as URL, type, data, success/failure
handlers, etc.

Question 5:In Django, which decorator is used to protect views from Cross-Site Request
Forgery (CSRF) attacks when handling AJAX requests?

A) @csrf_exempt(corret)

B) @csrf_protect

C) @csrf_token

D) @csrf_ajax

MALLIKARJUNA GD Page277 | 280


21CS62 Course Title : Fullstack Development

Explanation: The @csrf_exempt decorator is used in Django to exempt a view from CSRF
protection, which may be necessary when handling AJAX requests from external sources.

Question 6: What is the purpose of the JSON format in AJAX requests and responses?

A) To define document structure

B) To handle XML data

C) To provide a lightweight data interchange format(correct)

D) To manipulate DOM elements

Explanation: JSON (JavaScript Object Notation) is commonly used in AJAX requests and
responses due to its simplicity and lightweight nature, making it ideal for transmitting data
between the client and server.

Question 7:Which jQuery method is used to parse JSON data received from the server?

A) $.parseJSON()(correct)

B) $.getJSON()

C) $.ajax()

D) $.postJSON()

Explanation: The $.parseJSON() method is used in jQuery to parse a JSON string and convert
it into a JavaScript object.

Question 8: What is the purpose of the beforeSend function in a jQuery AJAX request?

A) To execute after the AJAX request is completed

B) To handle errors that occur during the AJAX request

C) To execute before the AJAX request is sent to the server(correct)

D) To execute when the AJAX response is received from the server

Explanation: The beforeSend function in a jQuery AJAX request is used to execute code before
the request is actually sent to the server, allowing for tasks such as modifying headers or
showing loading indicators.

Question 9: Which jQuery method is used to set up event handlers for AJAX requests that are
in progress?

A) .ajaxStart()

B) .ajaxSend()(correct)

C) .ajaxComplete()

MALLIKARJUNA GD Page278 | 280


21CS62 Course Title : Fullstack Development

D) .ajaxError()

Explanation: The .ajaxSend() method in jQuery is used to set up a function to be called


whenever an AJAX request is about to be sent.

Question 10:What is the purpose of the success function in a jQuery AJAX request?

A) To execute before the AJAX request is sent to the server

B) To execute when the AJAX response is received from the server(correct)

C) To handle errors that occur during the AJAX request

D) To execute after the AJAX request is completed

Explanation: The success function in a jQuery AJAX request is used to handle the data returned
from the server when the request is successful.

MALLIKARJUNA GD Page279 | 280


21CS62 Course Title : Fullstack Development

About the Author


Mallikarjuna G D brings over 20 years of invaluable expertise to the realm of technology and
education. As a seasoned technologist, he has delved deep into various facets of the education
sector, serving as both a Trainer and Developer.

His journey in the field of technology has been marked by a passion for continuous learning and
innovation. Mallikarjuna's diverse experience has equipped him with a comprehensive
understanding of the intricate dynamics within the educational landscape. Through his roles as a
Trainer and Developer, he has honed his skills in imparting knowledge and crafting solutions that
resonate with the evolving needs of the industry.

With a commitment to excellence and a penchant for staying ahead of the curve, Mallikarjuna
continues to make significant contributions to the intersection of technology and education. His
dedication to empowering others through education underscores his status as a revered figure in
the field.

In this book, Mallikarjuna shares his wealth of knowledge and insights, offering readers a valuable
resource that encapsulates years of experience and expertise. Prepare to embark on a journey of
discovery guided by a true visionary in the realm of technology and education.

MALLIKARJUNA GD Page280 | 280

You might also like