Django Framework23072024
Django Framework23072024
Django Framework
Django
DEVELOPMENT KIT
Django
DEVELOPMENT KIT
PREFACE
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.
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.
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.
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]
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
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.
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.
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.
and optimize system performance. This may include techniques such as load balancing,
caching, and asynchronous processing.
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.
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.
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:
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.
After installing Python, verify that it's installed correctly by opening the terminal or
command prompt and typing:
python --version
Virtual Environment
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.
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:
myworld\Scripts\activate.bat
Install Django:
Now, you can use pip to install Django. In the terminal or command prompt, type:
This command will download and install the latest version of Django from the Python
Package Index (PyPI) along with its dependencies.
After installing Django, you can verify the installation by running the following command:
django-admin --version
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.
cd myproject
This command will start the Django development server, and you should see output
indicating that the server is running.
Open a web browser and go to http://127.0.0.1:8000/admin/. You should see the Django
admin login page.
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.
• 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.
• 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.
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 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.
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.
Versio Releas
n e Year Key Features
0.9 2005 Initial public release
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:
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.
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.
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.
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')
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
requirements.txt: Lists the Python packages required for your project, which can be
installed using pip.
Example Content:
Django==4.0.3
djangorestframework==3.13.1
psycopg2-binary==2.9.3
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
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'your-secret-key'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
ROOT_URLCONF = 'myproject.urls'
TEMPLATES = [
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'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',
],
},
},
WSGI_APPLICATION = 'myproject.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.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/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
INSTALLED_APPS: Lists all Django applications that are activated in this project.
URLs.py: This file contains URL patterns for your project. It maps URL paths to views.
# urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
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
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
application = get_wsgi_application()
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
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
application = get_asgi_application()
__init__.py : Marks the directory as a Python package. Typically empty, but can be used to
set up package-level variables or imports.
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.
# apps.py
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
class MyModel(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.name
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
def my_view(request):
mymodels = MyModel.objects.all()
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
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.
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name='MyModel',
fields=[
('name', models.CharField(max_length=100)),
('description', models.TextField()),
],
),
tests.py:Contains tests for the application to ensure the code works as expected.
# tests.py
class MyModelTestCase(TestCase):
def setUp(self):
def test_model_creation(self):
test_model = MyModel.objects.get(name="Test")
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
• 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.
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.
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.
def post_list(request):
posts = Post.objects.all()
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.
html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Blog Posts</h1>
<ul>
{% 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.
• 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
mkvirtualenv mylearn
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.
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.
After we run the command above, it will generate the base folder structure for a Django
project.
| |-- 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.
Now everything is set up and we can run the server using the below command
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
myproject/
|-- myproject/
| | |-- 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
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.
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
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.
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:
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.
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
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.
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
def home(request):
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.
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.
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:
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
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:
def my_view(request):
Explaination:
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.
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.
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.
They provide an object-oriented way to define views, making it easier to reuse and organize
code.
class MyView(View):
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:
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.
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.
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.
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
urlpatterns = [
This code snippet is from a Django project's urls.py file, where URL patterns for routing
within the Django application are defined.
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.
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 = [
Line 3-5: This block defines the urlpatterns list, which contains URL patterns for routing
within the Django application.
• 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.
These views abstract away the repetitive code often written for CRUD (Create, Read, Update,
Delete) operations, making the development process faster and more efficient..
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:
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'
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.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Template</title>
</head>
<body>
</body>
</html>
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.
def home(request):
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.
In the template file, you can access the dynamic data passed from the view using template
language syntax (usually Django's template tags).
Setting.py
import os
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',
},
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.
urlpatterns = [
path('',home ,name='home'),
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.
They process form data and perform actions such as saving data to the database.
def my_form_view(request):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
else:
form = MyForm()
They can restrict access to certain views based on user permissions or roles.
@login_required
def my_protected_view(request):
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.
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.
def my_view(request):
class MyView(View):
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.
urlpatterns = [
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):
urlpatterns = [
path('myapp/', include('myapp.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.
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.
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.
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:
urlpatterns = [
orders/urls.py:
urlpatterns = [
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.
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:
urlpatterns = [
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
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:
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.
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:
urlpatterns = [
Solution: Ensure that each dynamic part of the URL has a corresponding route converter
specified. For example, <int:year> for integers.
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:
...
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).
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:
urlpatterns = [
Solution: Verify the view function name and import statement in your URLconf. Ensure the
view function is correctly defined and imported.
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:
Solution: Double-check the view name passed to the reverse() function. Ensure it matches
the name defined in your URLconf and is spelled correctly
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:
urlpatterns = [
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.
Internationalization and
django.utils.translation
Localization
Testing django.test
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
urlpatterns = [
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
def index(request):
def about(request):
Example:
# views.py
def index(request):
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
def index(request):
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
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.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:
def my_custom_sql():
row = cursor.fetchone()
return row
Example:
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:
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.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:
<html>
<head>
</head>
<body>
</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.
features. It allows users to sign up, log in, log out, reset passwords, and manage their
accounts.
Example:
# views.py
def login_view(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
login(request, user)
else:
else:
Example:
# settings.py
INSTALLED_APPS = [
...
'django.contrib.sessions',
MIDDLEWARE = [
...
'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
def my_view(request):
...
...
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:
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.
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
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
class MyModelAdmin(admin.ModelAdmin):
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
urlpatterns = [
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
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.
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.
Example:
# views.py
def my_view(request):
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
class MyModel(models.Model):
Example:
Example:
# settings.py
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
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:
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
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:
// 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:
Testing Views: You can test views by simulating HTTP requests and checking the responses
using test client provided by Django.
Example:
# tests.py
class MyViewTestCase(TestCase):
def test_view(self):
client = Client()
response = client.get(reverse('my_view'))
self.assertEqual(response.status_code, 200)
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 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.
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
You can access these settings from any part of your Django project by importing
django.conf.settings.
Example:
if settings.DEBUG:
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.
Example:
# urls.py
urlpatterns = [
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
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:
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.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.
3. Installation of Django:
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:
You'll know the virtual environment is activated when you see the environment name
(myenv) in your terminal prompt.
With the virtual environment activated, you can now install Django and create a new
project.
Once Django is installed, create a new Django project by running the following command:
Replace myproject with the name you want to give to your Django project.
cd myproject
Inside the Django project directory (myproject), you can create Django apps.
To create a new app within your project, run the following command:
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.
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.
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.
import datetime
def current_datetime(request):
now = datetime.datetime.now()
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.
urlpatterns = [
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.
urlpatterns = [
path('admin/', admin.site.urls),
path('datetime/', include('datetimeapp.urls')),
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.
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.
import datetime
def datetime_offset(request):
now = datetime.datetime.now()
context = {
'current_datetime': now,
'datetime_before': offset_before,
'datetime_after': offset_after
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">
</head>
<body>
</body>
</html>
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.
urlpatterns = [
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.
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')],
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.
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.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.
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?
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.
A) Model-View-Component
B) Model-View-Controller
C) Model-View-Template (Correct)
D) Model-Controller-Template
A) Authentication
B) URL routing
C) Database management
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.
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.
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.
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?
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.
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.
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.
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.
Template Language:
Template Files:
Context:
Template Engine:
Syntax :
Django's template syntax consists of special tags, variables, and filters enclosed within
Basic Features:
Project Structure:
myproject/
myapp/
templates/
myapp/
index.html
myproject/
settings.py
TEMPLATES = [
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'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',
],
},
},
Template (templates/myapp/index.html):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul>
{% endfor %}
</ul>
</body>
</html>
View:
def index(request):
context = {
Template Inheritance
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="content">
</div>
</body>
</html>
{% extends "base.html" %}
{% block content %}
<h1>Welcome to My Website</h1>
{% endblock %}
Variables : {{ variable_name }}
Control Structures
If statement:
{% if user.is_authenticated %}
{% else %}
Hello, Guest!
{% endif %}
For loop:
<ul>
{% endfor %}
</ul>
Filters
• date
• time
• length
• lower
• upper
• default
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<header>
{% block header %}
<h1>Default Header</h1>
{% endblock %}
</header>
<main>
</main>
<footer>
{% block footer %}
<p>Default Footer</p>
{% endblock %}
</footer>
</body>
</html>
{% extends "base.html" %}
{% block header %}
<h1>Custom Header</h1>
{% endblock %}
{% block content %}
{% endblock %}
{% block footer %}
{% 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.
Separation of Concerns:
Reusability:
Flexibility:
Efficiency:
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:
mkvirtualenv mytest
django-admin --version
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'helloapp'
urls.py
urlpatterns = [
path('', include('helloapp.urls')),
path('admin/', admin.site.urls),
You can render dynamic content in templates using variables passed via a context dictionary.
Views.py
def my_view(request):
context = {
'age': 45,
'is_registered': True
In the above example, the context dictionary contains data like username, age, and
is_registered, which can be accessed in the template.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Profile</title>
</head>
<body>
{% if is_registered %}
<p>Welcome back!</p>
{% else %}
{% 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.
Output:
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.
Although Django comes with its own templating system, you can use Jinja2 if you prefer its syntax
and features.
Install Jinja2:
TEMPLATES = [
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'APP_DIRS': True,
'OPTIONS': {
'environment': 'your_project.jinja2.environment',
},
},
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'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 file jinja2.py in your project directory and define the Jinja2 environment:
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
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.
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.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
</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
def my_view(request):
context = {
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
urlpatterns = [
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.
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.
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 %}
3. {% block %}: Used in template inheritance to define blocks that child templates can
override.
1. {{ variable|filter }}: Filters allow you to modify the output of template variables.
Django provides several built-in filters for common tasks.
2. safe: Marks a string as safe HTML, preventing Django from escaping it. Use with
caution to avoid XSS vulnerabilities.
{{ unsafe_html|safe }}
{{ items|length }}
{{ 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
to your HTML templates. You can also create custom template tags and filters to extend
Django's template system further.
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
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
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.
# views.py
def post_list(request):
posts = Post.objects.all()
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.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog</title>
</head>
<body>
<h1>Blog Posts</h1>
<ul>
{% 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
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.
cd myblogproject
2. Define Models:
# blog/models.py
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:
# blog/views.py
def post_list(request):
posts = Post.objects.all()
4. Create Templates:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog</title>
</head>
<body>
<h1>Blog Posts</h1>
<ul>
{% endfor %}
</ul>
</body>
</html>
5. Define URLs:
# blog/urls.py
urlpatterns = [
Include the app's URLs in the project's main URL configuration in the myblogproject/urls.py file.
# myblogproject/urls.py
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.
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.
1. Template Directories:
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': [
],
'APP_DIRS': True,
'OPTIONS': {
},
},
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.
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.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<header>
<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>
</footer>
</body>
</html>
{% extends 'base.html' %}
{% block content %}
{% 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.
# views.py
def home(request):
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
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.
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.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '5432',
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '3306',
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.
models.py:
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
published_date = models.DateField()
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
class Product(models.Model):
stock = models.IntegerField()
4. FloatField
class Product(models.Model):
price = models.FloatField()
5. DateField
class Event(models.Model):
event_date = models.DateField()
6. DateTimeField
class Event(models.Model):
start_time = models.DateTimeField()
7. BooleanField
class Task(models.Model):
completed = models.BooleanField(default=False)
8. ForeignKey
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=200)
9. ManyToManyField
class Author(models.Model):
name = models.CharField(max_length=100)
birth_date = models.DateField()
class Publisher(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=200)
published_date = models.DateField()
price = models.FloatField()
description = models.TextField()
available = models.BooleanField(default=True)
def __str__(self):
return self.title
3. Field Options
null: If True, Django will store empty values as NULL in the database.
primary_key: If True, this field is the primary key for the model.
class Book(models.Model):
author = models.CharField(max_length=100)
published_date = models.DateField()
('fiction', 'Fiction'),
('nonfiction', 'Non-Fiction'),
('biography', 'Biography'),
])
available = models.BooleanField(default=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()
class Meta:
ordering = ['title']
verbose_name = 'book'
verbose_name_plural = 'books'
def __str__(self):
return self.title
5. Model Methods
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()
def __str__(self):
return self.title
def is_recent(self):
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:
class UserProfile(models.Model):
bio = models.TextField()
website = models.URLField()
class User(models.Model):
username = models.CharField(max_length=100)
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)
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)
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")
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)
class Enrollment(models.Model):
date_enrolled = models.DateField()
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.
related_name Parameter:
This parameter specifies the name of the reverse relation from the related model back to this
one.
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.
through_fields Parameter:
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.
By leveraging these relationship fields, you can create complex and meaningful relationships
between your Django models, enabling a rich and connected data structure.
1. Creating Records
To create records, you instantiate a model and call the save() method, or use the create()
method.
author.save()
book = Book(
title=’Mahabharath’,
published_date='2024-06-08',
price=2229.99,
stock=50,
available=True,
author=author
book.save()
book = Book.objects.create(
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.
authors = Author.objects.all()
books = Book.objects.all()
author = Author.objects.get(pk=1)
book = Book.objects.get(title='1984')
available_books = Book.objects.filter(available=True)
expensive_books = Book.objects.filter(price__gt=10)
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.
# Retrieve a book
book = Book.objects.get(pk=1)
book.price = 10.99
book.stock = 40
book.save()
You can also use the update() method to update multiple records at once.
Book.objects.all().update(available=True)
Book.objects.all().update(price=F('price') + 1)
4. Deleting Records
# Retrieve a book
book = Book.objects.get(pk=1)
book.delete()
Book.objects.filter(author__name='SWAMY').delete()
Book.objects.filter(stock=0).delete()
# 1. Create
book1 = Book.objects.create(
published_date='1997-06-26',
price=20.00,
stock=100,
available=True,
author=author1
book2 = Book.objects.create(
title='The Hobbit',
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()
available_books = Book.objects.filter(available=True)
# 3. Update
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.delete()
Author.objects.filter(name='J.K. Rowling').delete()
In this example:
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.
• 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
Author Model
Let's say we have an Author model. We want to see the author's name when we view the
author object.
class Author(models.Model):
name = models.CharField(max_length=100)
birth_date = models.DateField()
class Author(models.Model):
name = models.CharField(max_length=100)
birth_date = models.DateField()
def __str__(self):
return self.name
Book Model
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)
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)
def __str__(self):
return self.title
Publisher Model
For a Publisher model, the publisher's name would be a suitable string representation.
class Publisher(models.Model):
name = models.CharField(max_length=100)
class Publisher(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
Here’s the complete example with __str__ methods added to all relevant 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
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)
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):
bio = models.TextField()
def __str__(self):
return self.user.username
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
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})
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:
cd event_project
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:
# event_app/views.py
def fruit_list(request):
def student_list(request):
4. Create Templates:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fruit List</title>
</head>
<body>
<h1>List of Fruits</h1>
<ul>
{% endfor %}
</ul>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student List</title>
</head>
<body>
<ol>
{% endfor %}
</ol>
</body>
</html>
5. Define URLs:
# event_app/urls.py
urlpatterns = [
Include the app's URLs in the project's main URL configuration in the event_project/urls.py file.
# event_project/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('event/', include('event_app.urls')),
Since we're not using any models in this example, there's no need to run migrations.
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.
Create a layout template named layout.html in the templates directory of your Django app.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<header>
<h1>My Website</h1>
<nav>
<ul>
</ul>
</nav>
</header>
<main>
{% block content %}
{% endblock %}
</main>
<footer>
</footer>
</body>
</html>
{% extends 'layout.html' %}
{% block content %}
{% endblock %}
{% extends 'layout.html' %}
{% block content %}
<h2>About Us</h2>
{% endblock %}
{% extends 'layout.html' %}
{% block content %}
<h2>Contact Us</h2>
{% endblock %}
3. Define URLs:
Define URL patterns for the three additional pages in the urls.py file of your app.
# urls.py
urlpatterns = [
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.
Now, you can visit the following URLs in your web browser:
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.
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):
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)
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.
Now, you can test the app in the Django admin interface. Run the development server:
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
2.9. MCQ
Question 1: What is the purpose of Django's template system?
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.
A) render_template()
B) render_to_response()
C) render() (correct)
D) render_view()
Explanation: The render() function in Django views is used to render templates by combining
them with a given context.
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.
B) Improved security
Explanation: Django's template system helps in organizing code by separating presentation logic
from business logic, making it easier to maintain and understand.
A) {% if %}
B) {{ variable|date }} (correct)
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.
C) Create a base template with common elements and extend it in child templates(correct)
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.
Explanation: If a block is not overridden in a child template, Django renders the content of that
block as defined in the parent template.
Explanation: Django supports multiple levels of template inheritance, allowing child templates
to serve as parent templates for other child templates.
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.
• 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:
Internationalization:
• 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.
First, make sure you have Django installed. You can install it via pip if you haven't already:
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.
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:
Once you've created the superuser account, you can start the Django development server:
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.
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.
• 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.
• 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.
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:
Authentication Backends:
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
urlpatterns = [
# 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:
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:
The @permission_required decorator can be used to protect views that require specific
permissions.
Example Usage:
# models.py
class CustomUser(AbstractUser):
pass
# admin.py
admin.site.register(CustomUser, UserAdmin)
# views.py
@login_required
def my_view(request):
@permission_required('myapp.special_permission')
def special_view(request):
Custom Permissions:
# custom_backend.py
class CustomBackend(BaseBackend):
User = get_user_model()
try:
user = User.objects.get(username=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
User = get_user_model()
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
# 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.
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',
'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/
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)
class BookInlineForm(forms.ModelForm):
class Meta:
model = Book
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)
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)
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.
• Django Model Forms (forms.ModelForm): Tied to Django models for creating and updating
instances.
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.
A form class is created by inheriting from forms.Form. You define fields as class attributes.
Example:
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
In this example:
To display the form in an HTML template, you create an instance of the form and pass it to the
template context.
View:
def contact_view(request):
form = ContactForm()
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>
</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.
When the form is submitted, you handle the POST request, validate the form data, and process
the valid data.
View:
def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
else:
form = ContactForm()
If the form is not valid, the form instance will contain error messages, which can be displayed
in the template.
4. Form Validation
Django forms provide built-in validation for common fields, and you can also add custom
validation.
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'):
return email
clean_<fieldname> methods are used to add custom validation for individual fields.
Widgets define how form fields are rendered. You can customize them or use built-in widgets.
Example:
class ContactForm(forms.Form):
The attrs parameter allows you to add HTML attributes to the rendered form fields.
Django automatically handles form errors and displays them in the template.
Template example:
<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.
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:
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)
super().__init__(*args, **kwargs)
if some_condition:
self.fields['email'].required = True
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.
• 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.
• 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
cd mysite
# contact/models.py
class Contact(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
message = models.TextField()
def __str__(self):
return self.name
# contact/forms.py
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
Define views to render the form and handle form submission in contact/views.py.
# contact/views.py
def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
else:
form = ContactForm()
5. Configure URLs
# contact/urls.py
urlpatterns = [
# mysite/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('contact/', include('contact.urls')),
6. Create Templates
<!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>
</html>
Run the initial migrations to create the database tables and start the development server.
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 Meta class inside ContactForm specifies the model to use (Contact) and the fields to include
in the form (name, email, message).
Views:
If the request method is POST, the form is populated with the submitted data and validated.
If the form is not valid or it is a GET request, the form is rendered for the user to fill out.
Templates:
The template renders the form using {{ form.as_p }} to display each form field wrapped in a <p>
tag.
URLs:
The app’s URL configuration is included in the project’s main URL configuration.
Migrations are run to set up the database tables for the Contact model.
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.
class Project(models.Model):
student_name = models.CharField(max_length=100)
topic = models.CharField(max_length=200)
languages = models.CharField(max_length=200)
def __str__(self):
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
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()
def project_success_view(request):
urlpatterns = [
<!DOCTYPE html>
<html>
<head>
<title>Create Projects</title>
</head>
<body>
<h2>Create Projects</h2>
<form method="post">
{% csrf_token %}
{{ formset.management_form }}
{{ form.as_p }}
{% endfor %}
<button type="submit">Save</button>
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Projects Created</title>
</head>
<body>
</body>
</html>
Ensure that the main URL configuration includes the URLs from the projects app.
urlpatterns = [
path('admin/', admin.site.urls),
path('projects/', include('projects.urls')),
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
class FeedbackForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
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
def feedback_view(request):
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
else:
form = FeedbackForm()
Create an HTML template to render the feedback form. Include the form fields in the template
using Django template language. For example:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
</form>
Map the view to a URL pattern in your Django project's urls.py file:
# myproject/urls.py
urlpatterns = [
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.
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.
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.
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.
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
class MyForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
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
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']
else:
form = MyForm()
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):
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
Map the view to a URL pattern in your Django project's urls.py file:
# myproject/urls.py
urlpatterns = [
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.
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.
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.
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
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
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():
return name
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.
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.
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
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']
else:
form = MyForm()
Example Template:
<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.
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.
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
class MyModel(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
message = models.TextField()
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
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
Create an HTML template to render the model form. Include the form fields in the template
using Django template language. For example:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
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
urlpatterns = [
Define a view function or class-based view to render the model form and process form
submissions. For example:
# myapp/views.py
def my_form_view(request):
if request.method == 'POST':
form = MyModelForm(request.POST)
if form.is_valid():
form.save()
else:
form = MyModelForm()
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 }}).
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.
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.
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.
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.
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.
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.
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
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.
# myapp/urls.py
urlpatterns = [
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.
# myproject/urls.py
urlpatterns = [
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
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
Open a terminal or command prompt and follow these commands to create a new Django
project named myproject:
cd myproject
3. Define Models
# myapp/models.py
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):
class Course(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
def __str__(self):
return self.name
# myapp/admin.py
@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
list_filter = ('date_of_birth',)
@admin.register(Course)
class CourseAdmin(admin.ModelAdmin):
5. Perform Migrations
1. create view
# myapp/views.py
from django.shortcuts import render, get_object_or_404
from .models import Student, Course
# 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,
'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>
4. Create url
urlpatterns = [
path('student/<int:student_id>/', views.student_detail,
name='student_detail'),
path('course/<int:course_id>/', views.course_detail,
name='course_detail'),
]
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
6. Create a Superuser
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.
# myapp/models.py
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
Now, let's define the Student model with a foreign key relationship to the Project model:
# myapp/models.py
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
class Student(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
Next, create a model form for the Student model with fields for the project topic, languages
used, and duration:
# myapp/forms.py
class StudentForm(forms.ModelForm):
class Meta:
model = Student
topic = forms.CharField(max_length=100)
languages_used = forms.CharField(max_length=100)
duration = forms.CharField(max_length=50)
Now, you can display the StudentForm in a template to collect input from users:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
Define a view function to handle the form submission and save the data to the database:
# myapp/views.py
def student_form_view(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
student = form.save()
else:
form = StudentForm()
Map the student_form_view to a URL pattern in your project's urls.py file and configure the
URLconf:
# myproject/urls.py
urlpatterns = [
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.6 MCQ
Question 1: How do you activate the Django admin interface for your project?
Question 2: What actions can you perform using the Django admin interface?
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
Explanation: Django provides built-in options for customizing the admin interface, such as
overriding templates, customizing form fields, and adding custom actions.
Explanation: Form processing in Django involves handling HTTP POST requests sent from HTML
forms and extracting form data from the request.
Explanation: In Django, you can create a feedback form by defining a model form that
corresponds to a Feedback model.
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?
Explanation: In Django, you can implement custom validation for form fields by defining custom
validation methods within the form class.
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.
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?
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.
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.
1. ListView
Example:
# views.py
class TaskListView(ListView):
model = Task
template_name = 'task_list.html'
context_object_name = 'tasks'
2. DetailView
Example:
# views.py
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
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.
Example:
# views.py
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
class TaskDeleteView(DeleteView):
model = Task
template_name = 'task_confirm_delete.html'
success_url = reverse_lazy('task_list')
Benefits :
• Extensibility: You can extend and customize generic views to fit specific requirements by
overriding methods or combining multiple mixins.
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.
templates: Create HTML templates for listing, displaying, creating, updating, and deleting tasks.
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.
1. ListView
Example:
# views.py
def task_list_view(request):
tasks = Task.objects.all()
2. DetailView
Example:
# views.py
3. CreateView
Provides a form for creating a new object and saves the object upon form submission.
Example:
# views.py
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()
4. UpdateView
Provides a form for updating an existing object and saves the changes upon form submission.
Example:
# views.py
if request.method == 'POST':
if form.is_valid():
form.save()
return redirect('task_list')
else:
form = TaskForm(instance=task)
5. DeleteView
Provides a confirmation page for deleting an object and deletes the object upon confirmation.
Example:
# views.py
if request.method == 'POST':
task.delete()
return redirect('task_list')
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.
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.
views.py: Implement function-based views for listing, displaying, creating, updating, and
deleting tasks.
templates: Create HTML templates for listing, displaying, creating, updating, and deleting tasks.
Mixins:
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.
• 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.
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
class CustomLoginRequiredMixin(LoginRequiredMixin):
redirect_field_name = 'redirect_to'
This mixin ensures that any view using it requires the user to be logged in.
# tasks/views.py
model = Task
template_name = 'task_list.html'
context_object_name = 'tasks'
model = Task
template_name = 'task_detail.html'
context_object_name = 'task'
model = Task
form_class = TaskForm
template_name = 'task_form.html'
success_url = reverse_lazy('task_list')
model = Task
form_class = TaskForm
template_name = 'task_form.html'
success_url = reverse_lazy('task_list')
model = Task
template_name = 'task_confirm_delete.html'
success_url = reverse_lazy('task_list')
For function-based views, Django provides decorators, which work similarly to mixins for class-
based views.
# tasks/views.py
@login_required(login_url='/login/')
def task_list_view(request):
tasks = Task.objects.all()
@login_required(login_url='/login/')
@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()
@login_required(login_url='/login/')
if request.method == 'POST':
if form.is_valid():
form.save()
return redirect('task_list')
else:
form = TaskForm(instance=task)
@login_required(login_url='/login/')
if request.method == 'POST':
task.delete()
return redirect('task_list')
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
Example: Only allow users with specific permissions (e.g., can_add_task) to access a view.
permission_required = 'tasks.add_task'
2. UserPassesTestMixin
Purpose: Allows you to define custom access logic based on user attributes or conditions.
class GroupMembershipMixin(UserPassesTestMixin):
def test_func(self):
return self.request.user.groups.filter(name='Managers').exists()
3. FormMixin
form_class = TaskCommentForm
template_name = 'task_detail.html'
def get_success_url(self):
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
4. ContextMixin
class CommonContextMixin(ContextMixin):
context = super().get_context_data(**kwargs)
return context
5. Multiple Inheritance
Example: Use mixins for authentication, permissions, and additional context data together.
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
template_name = 'custom_template.html'
• 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.
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.
urlpatterns = [
Define your views by subclassing the appropriate generic views and specifying the model and
template attributes.
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'
class MyUpdateView(UpdateView):
model = MyModel
template_name = 'myapp/my_model_form.html'
class MyDeleteView(DeleteView):
model = MyModel
template_name = 'myapp/my_model_confirm_delete.html'
success_url = '/my-list/'
Create templates for your views if they don't already exist. These templates should match the
template_name attributes specified in your views.
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.
Define a custom view by subclassing the desired generic view and overriding methods or
attributes as needed.
class CustomListView(ListView):
model = MyModel
template_name = 'myapp/my_custom_list.html'
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(some_condition=True)
Define a URL pattern for your custom view in your project's urls.py file.
urlpatterns = [
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.
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.
You can also extend generic views by combining them with mixins. Mixins are reusable
components that provide additional functionality to views.
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.
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.
Define a custom view by subclassing the desired generic view and overriding methods or
attributes as needed.
class CustomListView(ListView):
model = MyModel
template_name = 'myapp/my_custom_list.html'
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(some_condition=True)
Define a URL pattern for your custom view in your project's urls.py file.
urlpatterns = [
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.
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.
You can also extend generic views by combining them with mixins. Mixins are reusable
components that provide additional functionality to views.
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.
• 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.
• 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:
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.
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:
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.
def download_file(request):
file_path = '/path/to/file.pdf'
return response
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']
if mime_type == 'application/pdf':
pass
pass
else:
pass
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:
import csv
def generate_csv(request):
response = HttpResponse(content_type='text/csv')
writer = csv.writer(response)
return response
def generate_pdf(request):
response = HttpResponse(content_type='application/pdf')
data = [
# Generate PDF
table = Table(data)
table.setStyle(style)
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.
Here's how you can use the syndication feed framework in Django:
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.
class LatestPostsFeed(Feed):
link = "/blog/"
def items(self):
return Post.objects.order_by('-published_date')[:5]
return item.title
return item.content
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.
urlpatterns = [
Include the URLs for your feeds in your project's main URLconf by using Django's include()
function.
urlpatterns = [
path('feeds/', include('myapp.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.
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.
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.
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.
class PostSitemap(Sitemap):
changefreq = 'weekly'
priority = 0.9
def items(self):
return Post.objects.all()
return obj.modified_date
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.
sitemaps = {
'posts': PostSitemap,
urlpatterns = [
If your site has multiple sitemap classes, you can register them with Django's Sitemap class in
your project's urls.py file.
sitemaps = {
'posts': PostSitemap,
'products': ProductSitemap,
urlpatterns = [
Once you've set up the sitemap URLs, search engines and other tools can access the sitemap
files by visiting the corresponding URLs.
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.
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.
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.
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.
Sure, here's a step-by-step example of how to handle cookies and sessions in Django:
cd myproject
Define views in your views.py file to demonstrate cookies and session handling.
def set_cookie(request):
response.set_cookie('my_cookie', 'cookie_value')
return response
def get_cookie(request):
my_cookie = request.COOKIES.get('my_cookie')
def set_session(request):
request.session['my_session'] = 'session_value'
def get_session(request):
my_session = request.session.get('my_session')
Configure URL patterns in your urls.py file to map URLs to the defined views.
urlpatterns = [
MIDDLEWARE = [
# Other middleware...
'django.contrib.sessions.middleware.SessionMiddleware',
# Other middleware...
Start the Django development server and navigate to the URLs defined in your views.
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.
let's create a simple Django example to demonstrate the usage of session objects:
def set_session(request):
request.session['username'] = 'john_doe'
def get_session(request):
Define URL patterns in your urls.py to map URLs to the defined views.
urlpatterns = [
MIDDLEWARE = [
# Other middleware...
'django.contrib.sessions.middleware.SessionMiddleware',
# Other middleware...
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.
Users:
Authentication:
Example Code:
def user_login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
login(request, user)
return redirect('home')
else:
else:
@login_required
def user_logout(request):
logout(request)
return redirect('login')
@login_required
def home(request):
In this example:
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
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:
class Student(models.Model):
name = models.CharField(max_length=100)
roll_number = models.CharField(max_length=20)
Define URL patterns in your urls.py file to map URLs to the class-based views.
urlpatterns = [
Create class-based views in your views.py file using Django's generic views.
class StudentListView(ListView):
model = Student
template_name = 'student_list.html'
class StudentDetailView(DetailView):
model = Student
template_name = 'student_detail.html'
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>
{% endfor %}
</ul>
</body>
</html>
student_detail.html:
<!DOCTYPE html>
<html>
<head>
<title>Student Details</title>
</head>
<body>
<h1>Student Details</h1>
</body>
</html>
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:
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.
In your Django app's views.py, define views for CSV and PDF generation.
import csv
def generate_csv(request):
response = HttpResponse(content_type='text/csv')
writer = csv.writer(response)
queryset = YourModel.objects.all()
return response
def generate_pdf(request):
response = HttpResponse(content_type='application/pdf')
queryset = YourModel.objects.all()
# Generate PDF
data = [[obj.field1, obj.field2, obj.field3] for obj in queryset] # Replace field1, field2, field3
with actual field names
table = Table(data)
table.setStyle(style)
doc.build([table])
return response
Define URL patterns in your app's urls.py to map URLs to the defined views.
urlpatterns = [
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.
• 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?
4.11 MCQ
Question 1. What is the purpose of Django's syndication feed framework?
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.
Explanation: You can generate a CSV file dynamically in Django using the built-in csv module
along with either HttpResponse or FileResponse class.
c) To authenticate users
Explanation: Cookies are used to store small pieces of data on the client's browser, including
session data, preferences, and tracking information.
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: Django's sitemap framework is used to generate XML sitemaps, which help search
engines discover and index the pages on your site.
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.
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?
Explanation: You can set the MIME type for a file download in Django using the content_type
attribute of the HttpResponse class.
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.
• 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.
• 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.
• 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.
• 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.
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.
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".
cd ajax_example
Define URLs:
# ajax_example/urls.py
urlpatterns = [
Create Templates:
Create HTML templates for the index page and the success page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form id="ajax-form">
<button type="submit">Submit</button>
</form>
<div id="result"></div>
</body>
</html>
// ajax_app/static/ajax_app/js/main.js
$(document).ready(function() {
$('#ajax-form').submit(function(event) {
$.ajax({
type: 'POST',
success: function(response) {
},
});
});
});
Define Views:
# ajax_app/views.py
def index(request):
def ajax_submit(request):
input_data = request.POST.get('input_data')
return JsonResponse(response_data)
else:
Finally, run the Django development server to see the application in action.
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.
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.
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.
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.
Example:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<script>
// JavaScript code to handle button click event and modify the heading text
document.getElementById("change-text").addEventListener("click", function() {
heading.style.color = "red";
});
</script>
</body>
</html>
In this example:
Quickglance:
Introduction to JavaScript
const PI = 3.14;
var test;
Control Structures
} else {
console.log(i);
Functions
function greet(name) {
console.log(greet("John"));
Arrow functions:
DOM Manipulation
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
setTimeout(function() {
console.log("Delayed message.");
try {
} catch (error) {
ES6 Features
console.log(`Hello, ${name}!`);
Asynchronous Programming
setTimeout(function() {
}, 2000);
});
promise.then(function(data) {
console.log(data);
});
fetch('https://api.example.com/data')
Local Storage
localStorage.setItem("name", "John");
document.addEventListener("click", function(event) {
if (event.target.matches("button")) {
console.log("Button clicked.");
});
Object-Oriented JavaScript
function Person(name) {
this.name = name;
Person.prototype.greet = function() {
};
console.log(john.greet());
Module Systems
// math.js
return a + b;
// app.js
Web APIs
navigator.geolocation.getCurrentPosition(function(position) {
console.log("Latitude:", position.coords.latitude);
console.log("Longitude:", position.coords.longitude);
});
function add(a, b) {
return a + b;
expect(add(1, 2)).toBe(3);
});
Performance Optimization
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.
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.
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.
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.
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.
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.
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.
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
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
def books_xml(request):
books = Book.objects.all()
URL Configuration:
# xml_example/urls.py
urlpatterns = [
Database Population:
Populate the database with some sample data using Django's admin interface or Django
shell.
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.
HttpRequest and HttpResponse are classes used to handle incoming requests from clients
and send responses back to them, respectively.
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.
Attributes/Methods:
Usage:
HttpResponse objects can be customized with response content, status code, and headers.
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:
cd myproject
Next, let's define a view that handles an HTTP request and sends back a simple HTTP
response.
def hello_world(request):
This view function, hello_world, takes an HttpRequest object as an argument and returns
an HttpResponse object with the content "Hello, World!".
urlpatterns = [
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.
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 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.
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:
Example:
Let's create a simple example to illustrate how HTML is used with Django templates:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<ul>
{% endfor %}
</ul>
</body>
</html>
View Function:
def index(request):
context = {
'current_date': datetime.now(),
urlpatterns = [
Static Files:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>About Us</title>
</head>
<body>
<h1>About Us</h1>
</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):
Key Concepts:
Example:
/* CSS code */
h1 {
color: blue;
font-size: 24px;
text-align: center;
<h1>This is a Heading</h1>
Selectors:
Box Model:
Example:
/* CSS code */
.box {
width: 200px;
height: 100px;
padding: 20px;
margin: 10px;
Flexbox:
Grid Layout:
Example:
/* CSS code */
.container {
display: flex;
justify-content: center;
align-items: center;
<div class="container">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</div>
Animations:
Transitions:
Example:
/* CSS code */
@keyframes slide {
0% { transform: translateX(0); }
.box {
width: 100px;
height: 100px;
background-color: blue;
<div class="box"></div>
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 */
.container {
flex-direction: column;
<div class="container">
<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.
First, make sure you have Django installed. You can install it via pip:
cd phone_directory
class Contact(models.Model):
name = models.CharField(max_length=100)
phone = models.CharField(max_length=20)
def __str__(self):
return self.name
admin.site.register(Contact)
def index(request):
contacts = Contact.objects.all()
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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>
{% endfor %}
</ul>
</div>
</body>
</html>
css
/* styles.css */
body {
background-color: #f4f4f4;
margin: 0;
padding: 0;
.container {
max-width: 800px;
padding: 20px;
background-color: #fff;
border-radius: 5px;
h1 {
color: #333;
ul {
list-style-type: none;
padding: 0;
li {
margin-bottom: 10px;
html
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.
"name": "Mallikarjuna",
"age": 30,
"is_student": false,
"address": {
"city": "Mysuru",
"state": "CA"
},
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
class Contact(models.Model):
name = models.CharField(max_length=100)
phone = models.CharField(max_length=20)
def to_json(self):
# serializers.py
class ContactSerializer(serializers.ModelSerializer):
class Meta:
model = Contact
Views:
# views.py
def get_contacts(request):
contacts = Contact.objects.all()
URL Configuration:
# urls.py
urlpatterns = [
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.
• 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.
cd myproject
Define a View:
def index(request):
Create a Template:
Create a directory named templates in the myapp directory. Inside templates, create a file
named index.html.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('#myButton').click(function() {
alert('Button clicked!');
});
});
</script>
</head>
<body>
</body>
</html>
Define URLs:
urlpatterns = [
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:
cd enrollment_project
Define Model:
In enrollment/models.py, define a model for Student with fields like name, email, and
course.
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:
class StudentForm(forms.ModelForm):
class Meta:
model = Student
Create a View:
def register_student(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()
else:
else:
form = StudentForm()
Create a Template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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',
data: $(this).serialize(),
success: function(response) {
if (response.success) {
alert('Registration successful!');
} else {
},
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:
urlpatterns = [
urlpatterns = [
path('admin/', admin.site.urls),
path('enrollment/', include('enrollment.urls')),
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.
cd search_project
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)
def __str__(self):
return self.name
def search(request):
def search_student(request):
query = request.GET['query']
students = Student.objects.filter(name__icontains=query)
else:
def get_courses(request):
student_id = request.GET['student_id']
courses = Course.objects.filter(student_id=student_id)
else:
urlpatterns = [
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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>
<ul id="studentList"></ul>
<div id="courseList"></div>
<script>
$(document).ready(function(){
$('#searchInput').on('input', function(){
$.ajax({
url: '/search_student/',
dataType: 'json',
success: function(data){
$('#studentList').empty();
data.forEach(function(student){
$('#studentList').append('<li data-student-
id="'+student.id+'">'+student.name+'</li>');
});
});
});
$.ajax({
url: '/get_courses/',
dataType: 'json',
success: function(data){
$('#courseList').empty();
data.forEach(function(course){
$('#courseList').append('<p>'+course.name+'</p>');
});
});
});
});
</script>
</body>
</html>
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.10 MCQ
Question 1: What does AJAX stand for?
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.
Explanation: jQuery simplifies JavaScript coding by providing easy-to-use methods for DOM
manipulation, event handling, and AJAX interactions.
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
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?
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?
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()
D) .ajaxError()
Question 10:What is the purpose of the success function in a jQuery AJAX request?
Explanation: The success function in a jQuery AJAX request is used to handle the data returned
from the server when the request is successful.
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.