Django Tutorial
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. This tutorial covers everything from MVT architecture to production-ready REST APIs.
What is Django?
Django was created in 2003 by Adrian Holovaty and Simon Willison at a newspaper company. It was released publicly in 2005. It follows the principle of "Don't Repeat Yourself" (DRY) and comes with everything built in.
Key Features
- ORM – powerful database abstraction; write Python instead of SQL.
- Admin interface – auto-generated admin panel from your models.
- Authentication – complete user auth system out of the box.
- Security – CSRF, XSS, SQL injection protection built in.
- URL routing – clean, flexible URL dispatcher.
- Template engine – Django Template Language (DTL).
- Scalable – powers Instagram, Pinterest, Mozilla, Disqus.
# Install Django pip install django # Create project django-admin startproject mysite # Create app cd mysite python manage.py startapp blog # Run dev server python manage.py runserver
Django MVT Architecture
Django follows the MVT (Model–View–Template) pattern. Understanding this flow is the key to understanding Django.
How MVT Works
- Model – defines data structure (maps to database table).
- View – business logic; processes requests, queries models, returns responses.
- Template – HTML with DTL tags; presentation layer.
Request Flow: Browser → URL Dispatcher → View → Model → Template → HTTP Response
MVT vs MVC
| MVC | Django MVT | Role |
|---|---|---|
| Model | Model | Data structure & DB |
| View | Template | Presentation / HTML |
| Controller | View | Business logic |
| Router | URL Dispatcher | Django handles this |
# models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title # views.py from django.shortcuts import render def post_list(request): posts = Post.objects.all().order_by('-created') return render(request, 'blog/post_list.html', {'posts': posts}) # urls.py from django.urls import path from . import views urlpatterns = [ path('', views.post_list, name='post-list'), path('<int:pk>/', views.post_detail, name='post-detail'), ] # Simulate the concept without Django installed print("Model → View → Template → Response") print("Django handles routing, ORM, and templating")
In Django's MVT, which component handles the business logic?
Django ORM Queries
The Django ORM lets you query the database using Python. Every query returns a QuerySet — lazy, chainable, and powerful.
Common QuerySet Methods
| Method | Description | Returns |
|---|---|---|
.all() | All objects | QuerySet |
.filter(**kwargs) | Matching objects | QuerySet |
.get(**kwargs) | Exactly one object | Object (or exception) |
.exclude(**kwargs) | Non-matching objects | QuerySet |
.order_by(field) | Sort results | QuerySet |
.count() | Number of objects | int |
.first() / .last() | First/last object | Object or None |
.values() | Dicts instead of objects | QuerySet |
select_related() for ForeignKey (SQL JOIN) and prefetch_related() for ManyToMany (separate query). Always check your query count with Django Debug Toolbar.# Simulating Django ORM field lookups in Python data = [ {"id": 1, "title": "Django Basics", "views": 120, "published": True}, {"id": 2, "title": "Django ORM", "views": 85, "published": True}, {"id": 3, "title": "Django REST API", "views": 200, "published": False}, {"id": 4, "title": "Django Signals", "views": 45, "published": True}, ] # Simulate: Post.objects.filter(published=True).order_by('-views') published = [p for p in data if p["published"]] published.sort(key=lambda x: -x["views"]) print("filter(published=True).order_by('-views'):") for p in published: print(f" {p['id']}. {p['title']:25} ({p['views']} views)") # Simulate: Post.objects.filter(title__icontains='django') search = [p for p in data if 'django' in p["title"].lower()] print(f"\nicontains('django'): {len(search)} results")
Django Authentication
Django's built-in auth system handles login, logout, registration, password hashing, sessions, and permissions out of the box.
Authentication vs Authorization
- Authentication – Who are you? (login/logout)
- Authorization – What can you do? (permissions, groups)
import hashlib, secrets # Simulate Django password hashing def make_password(raw_password): salt = secrets.token_hex(8) hashed = hashlib.sha256(f"{salt}{raw_password}".encode()).hexdigest() return f"sha256${salt}${hashed}" def check_password(raw_password, encoded): _, salt, hashed = encoded.split('$') return hashlib.sha256(f"{salt}{raw_password}".encode()).hexdigest() == hashed # Create user users_db = {} def create_user(username, password): users_db[username] = make_password(password) print(f"✓ User '{username}' created") def authenticate(username, password): if username in users_db: if check_password(password, users_db[username]): return True return False create_user("alice", "secure123") print("Login alice/secure123:", authenticate("alice", "secure123")) print("Login alice/wrong:", authenticate("alice", "wrong"))
Which Django decorator restricts a view to logged-in users only?
Django Coding Labs
10 hands-on labs simulating real Django patterns in runnable Python code.