Django in Python — Detailed Explanation
1. What is Django?
Django is a high-level Python web framework used to build secure, scalable, and database-driven web applications.
In simple words:
Django provides many ready-made tools for building complete web applications with Python.
Django can be used to build:
- Websites
- Web applications
- REST APIs
- E-commerce platforms
- Student management systems
- Blog systems
- Admin panels
- Social platforms
- Authentication systems
- Database-driven applications
2. Why Do We Need Django?
Python itself doesn't provide everything required to build a complete web application.
A web application needs things like:
User ↓ Browser ↓ HTTP Request ↓ Django ↓ URL Routing ↓ View ↓ Business Logic ↓ Database ↓ Response ↓ Browser
Django provides many of these components through one framework.
3. What is a Web Framework?
A web framework provides tools and structures for developing web applications.
Popular Python frameworks include:
| Framework | Main idea |
|---|---|
| Django | Full-featured web framework |
| Flask | Lightweight and flexible |
| FastAPI | Modern API-focused framework |
Django is often called a batteries-included framework because many common web-development features are available within the Django ecosystem.
4. Features of Django
Important Django features include:
- URL routing
- Views
- Models
- ORM
- Templates
- Forms
- Authentication
- Sessions
- Admin panel
- Middleware
- Static files
- Security features
- Database migrations
- Management commands
- Testing support
- Internationalization
- Application structure
5. Installing Django
First check Python:
python --version
On Windows:
py --version
Create a virtual environment:
python -m venv venv
Activate it.
Windows CMD
venv\Scripts\activate
Linux/macOS
source venv/bin/activate
Install Django:
pip install django
Check:
django-admin --version
6. Creating a Django Project
Create a project:
django-admin startproject myproject
Move into it:
cd myproject
Run the development server:
python manage.py runserver
You will normally get:
http://127.0.0.1:8000/
Open it in your browser.
7. Django Project Structure
After creating a project, you will usually see:
myproject/ │ ├── manage.py │ └── myproject/ ├── __init__.py ├── settings.py ├── urls.py ├── asgi.py └── wsgi.py
Let's understand these.
8. manage.py
manage.py is a command-line utility for managing your Django project.
Examples:
python manage.py runserver
python manage.py startapp students
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
9. settings.py
settings.py contains the project's configuration.
It controls things such as:
- Installed applications
- Database
- Middleware
- Templates
- Static files
- Time zone
- Security settings
- Allowed hosts
Example:
INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", ]
10. urls.py
urls.py controls URL routing.
Example:
from django.urls import path from . import views urlpatterns = [ path("", views.home), ]
This means:
/
is connected to:
views.home
11. wsgi.py
WSGI stands for:
Web Server Gateway Interface
It provides an interface between Django and WSGI-compatible web servers.
It is commonly relevant when deploying Django applications.
12. asgi.py
ASGI stands for:
Asynchronous Server Gateway Interface
It provides an interface between Django and ASGI-compatible servers.
It is useful for modern asynchronous features and protocols.
13. Project vs App
This is one of the most important Django concepts.
Project
The project is the complete Django website/application configuration.
App
An app is a component that handles a particular functionality.
For example:
Django Project │ ├── users ├── products ├── orders ├── payments └── blog
A project can contain multiple apps.
14. Creating an App
Run:
python manage.py startapp students
Structure:
students/ ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── tests.py ├── views.py └── migrations/
15. Registering an App
Add the app to settings.py:
INSTALLED_APPS = [ ... "students", ]
Now Django knows about the application.
16. Views
A view handles a request and returns a response.
Example:
from django.http import HttpResponse def home(request): return HttpResponse("Hello Django!")
17. Connecting View to URL
In urls.py:
from django.urls import path from students import views urlpatterns = [ path("", views.home), ]
Now:
http://127.0.0.1:8000/
will display:
Hello Django!
18. Request and Response
The basic flow is:
Browser ↓ Request ↓ URL ↓ View ↓ Processing ↓ Response ↓ Browser
Django represents an incoming request with an HttpRequest object.
A view returns a response such as:
HttpResponse()
19. URL Parameters
Django allows parameters in URLs.
path("student/<int:id>/", views.student)
View:
def student(request, id): return HttpResponse(f"Student ID: {id}")
URL:
/student/101/
Output:
Student ID: 101
20. Templates
Writing all HTML inside Python isn't practical.
Django provides a template system.
Create:
templates/ home.html
Example:
<!DOCTYPE html> <html> <head> <title>Django</title> </head> <body> <h1>Welcome to Django</h1> </body> </html>
View:
from django.shortcuts import render def home(request): return render(request, "home.html")
21. Passing Data to Templates
View:
def home(request): name = "Uday" return render( request, "home.html", {"name": name} )
Template:
<h1>Hello {{ name }}</h1>
Output:
Hello Uday
22. Django Template Language
Django has its own template syntax.
Display data
{{ name }}
Condition
{% if age >= 18 %} <p>Adult</p> {% else %} <p>Minor</p> {% endif %}
Loop
{% for student in students %} <p>{{ student }}</p> {% endfor %}
23. Static Files
Static files include:
- CSS
- JavaScript
- Images
Typical structure:
static/ ├── css/ │ └── style.css ├── js/ │ └── script.js └── images/ └── logo.png
In templates:
{% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}">
24. Models
A model represents data that Django stores in a database.
For example, a student model:
from django.db import models class Student(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() email = models.EmailField()
This describes the structure of student data.
25. Django ORM
Django includes an ORM.
ORM means:
Object-Relational Mapping
It allows you to work with database records using Python objects instead of writing SQL for every operation.
For example:
Student.objects.all()
instead of manually writing:
SELECT * FROM student;
26. Creating Database Tables
After creating or changing a model:
python manage.py makemigrations
Then:
python manage.py migrate
makemigrations
Creates migration instructions based on model changes.
migrate
Applies those changes to the database.
27. Creating Data
Example:
student = Student( name="Uday", age=21, email="uday@example.com" ) student.save()
This creates a database record.
28. Reading Data
Get all students:
students = Student.objects.all()
Get one:
student = Student.objects.get(id=1)
Filter:
students = Student.objects.filter(age=20)
29. Updating Data
student = Student.objects.get(id=1) student.age = 22 student.save()
30. Deleting Data
student = Student.objects.get(id=1) student.delete()
So Django ORM supports:
Create Read Update Delete
These are called CRUD operations.
31. Django Admin Panel
One of Django's well-known features is its built-in admin interface.
Create an administrator:
python manage.py createsuperuser
Enter:
Username Email Password
Then run:
python manage.py runserver
Open:
/admin/
You can log into the admin panel.
32. Registering Models in Admin
In:
students/admin.py
write:
from django.contrib import admin from .models import Student admin.site.register(Student)
Now the Student model can be managed through Django's admin interface.
33. Forms
Django provides a form system for handling user input.
Example:
from django import forms class StudentForm(forms.Form): name = forms.CharField(max_length=100) age = forms.IntegerField() email = forms.EmailField()
Forms can handle:
- Input validation
- Data processing
- Error messages
- HTML form generation
34. Model Forms
If the form corresponds to a database model, you can use ModelForm.
from django import forms from .models import Student class StudentForm(forms.ModelForm): class Meta: model = Student fields = ["name", "age", "email"]
This reduces repetitive code.
35. Authentication
Django includes built-in authentication functionality.
It provides support for:
- Users
- Passwords
- Login
- Logout
- Permissions
- Groups
- Sessions
Django provides authentication components through its built-in apps.
36. Middleware
Middleware is software that runs during the request/response processing process.
Simplified:
Request ↓ Middleware ↓ URL ↓ View ↓ Middleware ↓ Response
Middleware can be used for things such as:
- Authentication
- Sessions
- Security
- Logging
- Request processing
Example in settings.py:
MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", ]
37. Sessions
Django provides session support.
Sessions can store information associated with a user between requests.
Example:
request.session["username"] = "Uday"
Retrieve:
username = request.session.get("username")
Sessions are commonly used for:
- Login state
- Shopping carts
- Temporary user information
38. Django Security
Django includes several security mechanisms and secure defaults, including protections/features related to:
- CSRF
- XSS
- SQL injection through ORM query construction
- Clickjacking
- Secure password handling
- Host validation
However, developers still need to configure and use Django correctly. No framework automatically makes an application completely secure.
39. CSRF Protection
CSRF means:
Cross-Site Request Forgery
Django provides CSRF protection for forms.
Example:
<form method="POST"> {% csrf_token %} <input type="text" name="username"> <button type="submit"> Submit </button> </form>
The CSRF token helps Django verify that the request is legitimate.
40. Django REST API
Django can also be used to create APIs.
A commonly used ecosystem tool is Django REST Framework (DRF).
For example:
Frontend ↓ HTTP / JSON ↓ Django REST API ↓ Django ORM ↓ Database
DRF provides tools for:
- Serializers
- API views
- Authentication
- Permissions
- Routers
- Browsable APIs
41. Django Architecture
Django is commonly described using MTV.
MTV means:
M → Model T → Template V → View
Model
Handles data and database representation.
Template
Handles presentation/UI.
View
Handles request processing and application logic.
42. Django MTV Flow
User ↓ Browser ↓ URL Request ↓ URLconf ↓ View ↙ ↘ Model Template ↓ ↓ Database HTML \ / Response ↓ Browser
43. Django Project Structure
A more complete project might look like:
school/ │ ├── manage.py │ ├── school/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ ├── asgi.py │ └── wsgi.py │ ├── students/ │ ├── migrations/ │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── models.py │ ├── tests.py │ └── views.py │ ├── templates/ │ └── home.html │ └── static/ ├── css/ ├── js/ └── images/
44. Django URL → View → Template
Suppose we have:
URL
path("students/", views.students)
View
def students(request): students = Student.objects.all() return render( request, "students.html", {"students": students} )
Template
{% for student in students %} <h3>{{ student.name }}</h3> {% endfor %}
Database
Student Table ---------------- id name age email
The complete flow becomes:
Browser ↓ /students/ ↓ URL ↓ View ↓ ORM ↓ Database ↓ View ↓ Template ↓ HTML ↓ Browser
45. Django Commands You Should Know
| Command | Purpose |
|---|---|
django-admin startproject | Create project |
python manage.py runserver | Start development server |
python manage.py startapp | Create app |
python manage.py makemigrations | Create migrations |
python manage.py migrate | Apply migrations |
python manage.py createsuperuser | Create admin user |
python manage.py shell | Open Django Python shell |
python manage.py test | Run tests |
python manage.py collectstatic | Collect static files for deployment |
46. Database Support
Django's database layer supports several commonly used relational databases, including:
- SQLite
- PostgreSQL
- MySQL
- MariaDB
- Oracle
The database is configured in:
DATABASES
inside settings.py.
For example, a development project often starts with SQLite.
47. Django Migrations
Suppose you initially have:
class Student(models.Model): name = models.CharField(max_length=100)
Later you add:
age = models.IntegerField()
Run:
python manage.py makemigrations
Then:
python manage.py migrate
Django records these database structure changes as migrations.
48. Django Apps Example
Imagine you are building a college management system.
You might create:
college/ │ ├── students/ ├── teachers/ ├── courses/ ├── attendance/ ├── exams/ └── accounts/
Each app handles a particular part of the system.
This makes the project easier to organize.
49. Django vs Flask
| Django | Flask |
|---|---|
| Full-featured | Lightweight |
| Many features included | Minimal core |
| Built-in ORM | No built-in ORM |
| Built-in admin | No built-in admin |
| Built-in authentication system | Usually added/configured separately |
| MTV architecture | More flexible structure |
| Strong conventions | More freedom |
| Good for database-heavy applications | Good for small/medium apps and APIs |
| Larger framework | Smaller framework |
The choice depends on the project's requirements rather than one framework being universally better.
50. Django vs FastAPI
| Django | FastAPI |
|---|---|
| Full web framework | API-focused framework |
| Templates supported | Usually API/backend focused |
| ORM available | Database layer usually selected separately |
| Admin ecosystem | No built-in Django-style admin |
| Authentication ecosystem | Authentication usually assembled from available tools |
| MTV architecture | API-oriented architecture |
| Good for complete web applications | Good for API-heavy applications |
51. Advantages of Django
1. Batteries Included
Many common web-development features are available.
2. ORM
You can interact with databases using Python objects.
3. Admin Panel
You get a powerful administration interface.
4. Authentication
User and permission functionality is available.
5. Security Features
Django provides several built-in security mechanisms.
6. Scalability
Django can be used for applications ranging from small projects to large systems when properly designed and deployed.
7. Large Ecosystem
There are many third-party packages and learning resources.
52. Things to Consider
Django can feel more complex than Flask because it provides more structure and functionality.
You need to understand concepts such as:
Project App URL View Model ORM Template Form Middleware Migration Admin
For very small applications, this structure may feel heavier than a minimal framework.
53. Example: Student Management System
Django is particularly suitable for applications such as:
Student Management System │ ├── Login ├── Students ├── Teachers ├── Courses ├── Attendance ├── Exams ├── Results └── Admin Panel
Possible apps:
accounts students teachers courses attendance exams results
Database:
Users Students Teachers Courses Attendance Exams Results
Django can connect these components through models and relationships.
54. Django Learning Roadmap
Since you're learning Python, a useful sequence is:
Python ↓ Functions ↓ Modules & Packages ↓ Virtual Environment ↓ HTTP Basics ↓ Django Installation ↓ Project ↓ App ↓ URLs ↓ Views ↓ Templates ↓ Static Files ↓ Models ↓ ORM ↓ Migrations ↓ Admin ↓ Forms ↓ Authentication ↓ CRUD ↓ Middleware ↓ Django REST Framework ↓ Testing ↓ Deployment
55. Important Django Terms
| Term | Meaning |
|---|---|
| Django | Python web framework |
| Project | Complete Django application configuration |
| App | Component providing a specific functionality |
| URLconf | URL routing configuration |
| View | Handles requests and produces responses |
| Model | Defines database data |
| ORM | Maps Python objects to database operations |
| Template | HTML presentation layer |
| Migration | Database schema change system |
| Admin | Built-in administration interface |
| Middleware | Request/response processing layer |
| Form | Handles user input and validation |
| Session | Stores user-related data between requests |
| Static files | CSS, JavaScript, images |
| DRF | Django REST Framework for API development |
56. Django in One Picture
DJANGO │ ┌──────────────┼──────────────┐ ↓ ↓ ↓ URLs Views Models │ │ │ │ │ ORM │ │ │ │ ↓ ↓ │ Templates Database │ │ └──────────────┼──────────────┘ ↓ Response ↓ Browser
Short exam definition
Django is a high-level, open-source Python web framework used to develop secure, scalable, and database-driven web applications. It provides features such as URL routing, views, templates, ORM, authentication, forms, migrations, and an administrative interface.