Python Django
Tutorial 55 of 65 · pythondeck.com Python course
Django is a batteries-included web framework: ORM, migrations, admin, templates, auth, forms, sessions. Great for content-heavy applications and APIs (with Django REST Framework).
Django is batteries-included: ORM, admin, auth, migrations, and templating accelerate full-stack web apps with consistent conventions.
Teams adopt Django for rapid delivery and long-term maintainability when domain logic maps cleanly to relational models.
The framework encodes decades of web security lessons—CSRF middleware, password hashing, and template auto-escaping—so beginners inherit safer defaults than rolling their own stack.
Project vs apps — reusable apps; settings module per environment.
Models & migrations — schema as code; makemigrations/migrate workflow.
Views — function-based and class-based; prefer CBVs for CRUD patterns.
URLs & DRF — path converters; Django REST Framework for APIs.
Admin — rapid internal tooling with permissions.
Middleware & signals — cross-cutting concerns; use sparingly to avoid spaghetti.
The ORM lazy-loads relations—use select_related and prefetch_related in list views to avoid N+1 queries. Custom managers encode common filters. For high-traffic read paths, cache fragments or denormalize with Celery jobs updating search indexes.
Security defaults improve over versions: CSRF, XSS escaping in templates, password hashers. Still audit ALLOWED_HOSTS, DEBUG=False in prod, and store media on object storage not local disk.
Celery or Django-Q offload email, thumbnails, and report generation. Cache framework backends (Redis) speed template fragments; invalidate keys when models change via signals or explicit cache.delete in save().
Fat models and god views mixing HTTP, email, and business rules.
Raw SQL in loops instead of ORM aggregation or annotate.
Running migrations manually on multi-node deploys without coordination.
Serializing ORM models directly exposing internal fields in APIs.
Keep settings split (base/local/prod); use django-environ for secrets.
Write tests for models (constraints) and API contracts (pytest + factory_boy).
Use DRF serializers with explicit fields and validation.
Monitor with Sentry and APM on database query counts per endpoint.
Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.
The program below demonstrates start project. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# Example: Start project
# Run in the REPL or save as a .py file and execute with python.
pip install django
django-admin startproject site .
python manage.py startapp blog
python manage.py migrate
python manage.py runserver
This sample walks through model + admin in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# blog/models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
def __str__(self): return self.title
# blog/admin.py
from django.contrib import admin
from .models import Post
admin.site.register(Post)
Here is a hands-on illustration of view + url. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.
# blog/views.py
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello from Django")
# site/urls.py
from django.urls import path
from blog.views import hello
urlpatterns = [path("", hello)]
The program below demonstrates model define. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# Django ORM maps classes to SQL tables
# Inside models.py of a Django app:
from django.db import models # ORM base
class Book(models.Model): # table books
title = models.CharField(max_length=200) # varchar column
pages = models.PositiveIntegerField(default=0) # unsigned int
created = models.DateTimeField(auto_now_add=True) # timestamp
def __str__(self): # admin display
return self.title # human-readable
# Run: python manage.py makemigrations && migrate
This sample walks through view shortcut in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# Generic views reduce boilerplate for common patterns
from django.views.generic import ListView # class-based list
from .models import Book # local models
class BookList(ListView): # CBV configuration
model = Book # queryset source
template_name = "books/list.html" # template path
context_object_name = "books" # template variable
paginate_by = 20 # page size
# urls.py: path("books/", BookList.as_view())