Introduction to Django
Django is a high-level Python web framework designed for rapid development of secure, scalable, and maintainable web applications. It provides batteries-included tooling so you can focus on business logic instead of reinventing common web patterns.
Django ships with an ORM, authentication, admin, forms, validation, and templating out of the box. This makes it especially strong for data-driven websites and APIs where consistency, security, and speed of development matter.
Why Django?
- Fast development with built-in conventions and tools
- Secure by default (CSRF, SQL injection protection, XSS mitigation)
- Scalable and production-ready with caching, middleware, and async views
- Powerful ORM for database modeling and migrations
- Rich ecosystem and real-world adoption (Instagram, Pinterest, Mozilla)
Django Installation
# Check Python version
python --version
# Install Django
pip install django
# Verify installation
django-admin --version
Use a virtual environment to isolate dependencies and keep your project reproducible.
# Create and activate a virtual environment
python -m venv .venv
source .venv/bin/activate # macOS/Linux
# .venv\\Scripts\\activate # Windows
# Pin Django version
pip install "Django>=4.2,<5.1"
pip freeze > requirements.txt
Create Django Project
django-admin startproject myproject
cd myproject
python manage.py runserver
The project contains global settings and entry points for ASGI/WSGI. The manage.py script is your main command interface.
Project Structure
myproject/
βββ manage.py
βββ myproject/
β βββ settings.py
β βββ urls.py
β βββ asgi.py
β βββ wsgi.py
Key files:
settings.pydefines apps, middleware, templates, database, and security settingsurls.pyroutes requests to appsasgi.pyenables async servers and WebSocketswsgi.pyis the production entry point for WSGI servers
Create Django App
python manage.py startapp core
Apps are reusable, modular units. Organize your project by domain (e.g., blog, accounts) instead of by file type.
App Structure
core/
βββ admin.py
βββ apps.py
βββ models.py
βββ views.py
βββ tests.py
INSTALLED_APPS
URL Routing
URLs map browser requests to views. Django resolves patterns in order and stops at the first match.
# core/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
# myproject/urls.py
from django.urls import path, include
urlpatterns = [
path('', include('core.urls')),
]
Advanced routing features include path converters, namespacing, and reverse URL lookup.
path('users//', views.profile, name='profile')
app_name = "core"
# Reverse lookup: reverse('core:profile', args=[1])
Views
Views handle request logic and return responses. They can return HTML, JSON, redirects, or files.
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello Django")
from django.shortcuts import render
def about(request):
return render(request, 'about.html')
Use JsonResponse for API responses and handle methods explicitly.
from django.http import JsonResponse
def api_status(request):
return JsonResponse({"ok": True})
Templates
templates/
βββ core/
βββ home.html
Welcome
def home(request):
return render(request,'core/home.html',{'name':'Django'})
Templates support inheritance, filters, and template tags to keep layouts consistent.
{% block content %}{% endblock %}
{% extends "base.html" %}
{% block content %}{{ name|upper }}
{% endblock %}
Static Files (CSS, JS, Images)
static/
βββ css/style.css
βββ js/app.js
βββ images/logo.png
<link rel="stylesheet" href="/static/css/main.css?v=20260308">
In production, collect static files to a single directory using collectstatic and serve them via a web server or CDN.
Models & Database
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
email = models.EmailField()
def __str__(self):
return self.name
python manage.py makemigrations
python manage.py migrate
Models define database schema and relationships. Use ForeignKey, ManyToManyField, and OneToOneField to model data.
class Course(models.Model):
title = models.CharField(max_length=120)
class Enrollment(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
Django ORM (Database Queries)
Student.objects.create(name="Ali", age=20)
Student.objects.all()
Student.objects.filter(age__gt=18)
Student.objects.get(id=1)
Student.objects.update(age=22)
Student.objects.delete()
QuerySets are lazy and chainable. Use select_related and prefetch_related to reduce database queries.
Student.objects.select_related().filter(age__gte=18)
Student.objects.prefetch_related('enrollment_set')
Django Admin Panel
python manage.py createsuperuser
from django.contrib import admin
from .models import Student
admin.site.register(Student)
Customize the admin with ModelAdmin to improve search, filters, and list display.
@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
list_display = ("name", "age", "email")
search_fields = ("name", "email")
list_filter = ("age",)
Forms & ModelForms
from django import forms
from .models import Student
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'
def add_student(request):
form = StudentForm(request.POST or None)
if form.is_valid():
form.save()
return render(request,'form.html',{'form':form})
Forms support validation via clean() and field-specific clean_field methods. Always include CSRF tokens in templates.
Authentication (Login / Signup)
from django.contrib.auth import authenticate, login, logout
user = authenticate(username=u, password=p)
login(request, user)
logout(request)
Use permissions and groups to manage access, and consider a custom user model early for extensibility.
Middleware
Middleware processes requests before views and responses after views. Order matters and can affect performance and security.
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
]
Custom middleware lets you add logging, auth checks, or request timing.
Class Based Views (CBV)
from django.views import View
from django.http import HttpResponse
class HomeView(View):
def get(self, request):
return HttpResponse("Hello CBV")
CBVs provide reusable patterns like ListView, DetailView, CreateView, and mixins for auth and permissions.
Django REST Framework (API)
pip install djangorestframework
from rest_framework import serializers
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = '__all__'
DRF adds viewsets, routers, permissions, authentication, and pagination to build robust APIs quickly.
Security Best Practices
- CSRF Protection
- Password Hashing
- SQL Injection Prevention
- XSS Protection
Also configure SECURE_SSL_REDIRECT, SESSION_COOKIE_SECURE, and keep SECRET_KEY out of source control.
Deployment
- Gunicorn
- Nginx
- Docker
- Heroku / AWS
DEBUG = False
ALLOWED_HOSTS = ['yourdomain.com']
Use environment variables for secrets, configure database URLs, and run collectstatic before deploying.