Home / Django / Introduction

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.
💡
Note: Django uses Python — make sure you understand Python OOP and functions before starting this course.
Shell – Setup
# 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

MVCDjango MVTRole
ModelModelData structure & DB
ViewTemplatePresentation / HTML
ControllerViewBusiness logic
RouterURL DispatcherDjango handles this
Python – Django Request Flow
# 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")
Try It – Django Concepts
Python
Code Editor
Output
Click ▶ Run…
Quick Quiz

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

MethodDescriptionReturns
.all()All objectsQuerySet
.filter(**kwargs)Matching objectsQuerySet
.get(**kwargs)Exactly one objectObject (or exception)
.exclude(**kwargs)Non-matching objectsQuerySet
.order_by(field)Sort resultsQuerySet
.count()Number of objectsint
.first() / .last()First/last objectObject or None
.values()Dicts instead of objectsQuerySet
💡
N+1 Problem: Use select_related() for ForeignKey (SQL JOIN) and prefetch_related() for ManyToMany (separate query). Always check your query count with Django Debug Toolbar.
Python – ORM Simulation
# 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")
Try It – ORM Queries
Python
Code Editor
Output
Click ▶ Run…

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)
Python – Auth Simulation
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"))
Try It – Auth Simulation
Python
Code Editor
Output
Click ▶ Run…
Quick Quiz

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.

Lab 1 – CRUD Simulation

Django CRUD Simulation
Python
Code Editor
Output
Click ▶ Run…

Lab 2 – Signal Simulation (post_save)

Django Signals Simulation
Python
Code Editor
Output
Click ▶ Run…