Questions 1–20 of 100 · 0 of 20 on this page marked learned
1.django-0001Easyfresher
What is Django, and how does its Model-Template-View (MTV) pattern work?
Django is a Python web framework that ships with an ORM, URL routing, templates, forms, an admin site and authentication. It follows MTV: the Model holds data and rules, the View is a Python function or class that handles a request, and the Template turns data into HTML. The URL configuration decides which view runs for each URL.
Full answer
Django is a full-stack Python web framework. "Full-stack" here means it gives you most parts of a web app in one package: a database layer (the ORM), URL routing, an HTML template engine, form handling, a ready-made admin panel, user login, and security protections such as CSRF and SQL injection defence. Current releases are Django 5.2 (a long-term support release) and newer 6.x versions.
Django calls its pattern MTV, which maps closely to the classic MVC idea:
Model: a Python class that describes a database table and the rules for its data. A Student model might have name and marks fields.
Template: a text file (usually HTML) with placeholders such as {{ student.name }}.
View: a Python function or class that receives an HttpRequest and returns an HttpResponse. It reads models and fills a template.
What MVC calls the "controller" is split in Django between the view and the URL configuration (urls.py), which maps a URL pattern to a view.
The flow for one request looks like this:
The browser asks for /students/7/.
Django runs the middleware chain (security, sessions, auth).
The URL resolver finds the matching pattern and calls the view with pk=7.
The view loads Student 7 through the ORM and renders a template.
The response goes back out through middleware to the browser.
Django suits content sites, admin-heavy business apps and APIs (with Django REST Framework). Its strength is that common needs already have a tested, documented answer, so a team writes less glue code.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.db import models, connection
from django.template import Context, Engine
from django.http import HttpResponse
# Model: data and rules
class Student(models.Model):
name = models.CharField(max_length=50)
marks = models.IntegerField()
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
editor.create_model(Student)
Student.objects.create(name="Asha", marks=91)
# Template: presentation
template = Engine().from_string("<p>{{ s.name }} scored {{ s.marks }}</p>")
# View: takes a request, returns a response
def student_detail(request, pk):
student = Student.objects.get(pk=pk)
return HttpResponse(template.render(Context({"s": student})))
response = student_detail(request=None, pk=1)
print(response.status_code)
print(response.content.decode())
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
200
<p>Asha scored 91</p>
Key points
Django is a batteries-included Python web framework
Model = data and rules, Template = presentation, View = request handling logic
urls.py plays the controller role together with views
Every request passes through middleware, the URL resolver, a view and back
Django 5.2 is the current LTS line
Common mistakes
Calling Django an MVC framework without explaining where the controller logic lives
Putting business rules in templates instead of models or services
Thinking the template is the 'view' in the MVC sense
Forgetting that middleware runs before and after every view
Follow-ups
Where would you put logic that is shared by several views?
What happens if two URL patterns match the same path?
When would you choose FastAPI or Flask over Django?
Tips
Walk through one request from URL to response; it shows you know the moving parts
Name two built-in features (admin, ORM, auth) and why they save time
Mention that Django REST Framework is the common choice for APIs on top of Django
2.django-0002Easyfresher
What is the difference between a Django project and a Django app?
A project is the whole website: settings, root URLs and the WSGI/ASGI entry points. An app is a reusable package that does one job, such as attendance or library, with its own models, views and migrations. A project contains many apps, listed in INSTALLED_APPS.
Full answer
A project is the container for one website. django-admin startproject college creates it, with settings.py (database, installed apps, middleware), the root urls.py, and wsgi.py / asgi.py, which web servers use to load the app.
An app is a Python package that handles one area of the business. python manage.py startapp attendance creates models.py, views.py, admin.py, apps.py, tests.py and a migrations/ folder. A college site might have students, attendance and library apps.
An app only becomes active when its name (or its AppConfig path) is added to INSTALLED_APPS. Django then:
finds its models and creates migrations for them,
loads its admin.py,
looks for templates in its templates/ folder and static files in static/,
runs its AppConfig.ready() method at startup, which is where signal handlers are usually connected.
Django itself is built from apps: django.contrib.auth, django.contrib.admin, django.contrib.sessions.
How big should an app be? A good test is whether you can describe it in one short sentence without "and". "Tracks book loans" is one app. "Handles books and fees and hostel rooms" is probably three. Apps that are too large become hard to test; apps that are too tiny create many cross-imports. Avoid circular dependencies, where app A imports models from app B and B imports from A.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "django.contrib.sessions", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.apps import apps
# Every entry in INSTALLED_APPS becomes an AppConfig
for config in apps.get_app_configs():
print(config.label, "->", config.name)
# Models are registered per app
print([m.__name__ for m in apps.get_app_config("auth").get_models()])
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
contenttypes -> django.contrib.contenttypes
auth -> django.contrib.auth
sessions -> django.contrib.sessions
school -> school
['Permission', 'Group', 'User']
Key points
Project = settings + root URLs + server entry points
App = one feature area with models, views, migrations
Apps are activated through INSTALLED_APPS
AppConfig.ready() runs once at startup
Django's own features are apps too
Common mistakes
Putting every model into one giant app
Creating an app but forgetting to add it to INSTALLED_APPS, so migrations are never generated
Importing models at module level inside AppConfig before the registry is ready
Naming an app the same as an existing Python module, such as 'test' or 'email'
Follow-ups
How would you split an online library system into apps?
What does AppConfig.ready() do and what should not go in it?
How do you make an app reusable across two projects?
Tips
Show a concrete split for a real domain, it proves you have designed one
Mention INSTALLED_APPS and what Django discovers from it
Bring up circular imports as the main risk of a poor split
3.django-0003Easyfresher
What is a Django model, and how do field types and options like null, blank and default work?
A model is a Python class that subclasses models.Model; each class maps to a table and each field to a column. Field types decide the column type and validation. null controls whether the database column may store NULL, blank controls whether forms may leave it empty, and default supplies a value when none is given.
Full answer
A model describes one kind of record. Django turns each model class into a database table, each field into a column, and each instance into one row.
Common field types:
CharField(max_length=...) for short text, TextField for long text
IntegerField, DecimalField(max_digits, decimal_places) for money (never FloatField for money, because floats round)
BooleanField, DateField, DateTimeField
EmailField, URLField, SlugField (text with extra validation)
ForeignKey, OneToOneField, ManyToManyField for relations
Options that confuse people:
null=True is about the database. The column can hold NULL.
blank=True is about validation. Forms and full_clean() allow an empty value.
default= is used when you create an object without that field.
unique=True adds a unique index.
choices= limits allowed values and gives get_FOO_display().
For text fields, the Django convention is to avoid null=True and use blank=True with an empty string, so there is only one "empty" value, not two (NULL and "").
Django adds an auto-increment primary key named id unless you define one. Since Django 3.2 the type comes from DEFAULT_AUTO_FIELD; new projects use BigAutoField, which became the default value in Django 6.0.
Saving with save() does not run validation. Call full_clean() (forms do this for you) to check max_length, choices and validators before saving.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from decimal import Decimal
from django.core.exceptions import ValidationError
from django.db import models, connection
class FeePayment(models.Model):
MODES = [("cash", "Cash"), ("upi", "UPI"), ("card", "Card")]
student_name = models.CharField(max_length=40)
amount = models.DecimalField(max_digits=8, decimal_places=2)
mode = models.CharField(max_length=4, choices=MODES, default="cash")
remarks = models.CharField(max_length=100, blank=True) # empty string, not NULL
paid_on = models.DateField(null=True, blank=True) # may be unknown
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
editor.create_model(FeePayment)
p = FeePayment.objects.create(student_name="Ravi", amount=Decimal("1250.50"), mode="upi")
print(p.id, p.amount, p.get_mode_display(), repr(p.remarks), p.paid_on)
bad = FeePayment(student_name="Meera", amount=Decimal("10.00"), mode="cheque")
try:
bad.full_clean()
except ValidationError as e:
print(sorted(e.message_dict))
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
1 1250.50 UPI '' None
['mode']
Key points
One model = one table, one field = one column
null is a database setting, blank is a validation setting
Use DecimalField for money
save() does not validate; full_clean() does
Text fields usually use blank=True without null=True
Common mistakes
Mixing up null and blank
Using FloatField for money and then seeing 0.30000000000000004
Assuming save() checks max_length or choices
Adding null=True to CharField and ending up with two kinds of empty value
Follow-ups
What does DEFAULT_AUTO_FIELD control?
How would you store a field whose value is computed from two others?
How do you add a validator to a field?
Tips
Give the null vs blank difference in one sentence each
Mention full_clean() when talking about validation
Use a money example to justify DecimalField
4.django-0004Easyfresher
What are Django migrations, and what is the difference between makemigrations and migrate?
Migrations are Python files that record changes to models so the database schema can follow the code. makemigrations compares models with the last migration state and writes new migration files. migrate applies unapplied migration files to the database and records them in the django_migrations table.
Full answer
A migration is a Python file inside an app's migrations/ folder. It lists operations such as CreateModel, AddField or AlterField. Migrations let the database schema change in step with the code, and let every developer and server reach the same schema.
Two commands do different jobs:
python manage.py makemigrations reads your models, compares them with the state built from existing migration files, and writes a new file such as 0002_student_roll_no.py. It does not touch the database.
python manage.py migrate reads migration files, checks the django_migrations table to see which ones already ran, and applies the rest in dependency order.
Other useful commands:
showmigrations lists migrations with [X] for applied ones.
sqlmigrate app 0002 prints the SQL a migration will run. Useful for review before production.
migrate app 0001 moves an app back to an earlier migration (if the operations are reversible).
makemigrations --check --dry-run fails if models changed without a migration. Good for CI.
Migration files are code. Commit them to version control, review them, and never edit an applied migration on a shared database. If two developers create 0003 on different branches, Django detects the conflict and makemigrations --merge creates a merge migration.
Adding a field without a default to a table that already has rows forces Django to ask for a one-off default, because existing rows need a value.
python
import os
import sys
import tempfile
from pathlib import Path
# Build a tiny app on disk so makemigrations has somewhere to write
root = Path(tempfile.mkdtemp())
app = root / "attendance"
(app / "migrations").mkdir(parents=True)
(app / "__init__.py").write_text("")
(app / "migrations" / "__init__.py").write_text("")
(app / "models.py").write_text(
"from django.db import models\n\n"
"class Attendance(models.Model):\n"
" roll_no = models.IntegerField()\n"
" present = models.BooleanField(default=True)\n"
)
sys.path.insert(0, str(root))
os.chdir(root)
import django
from django.conf import settings
settings.configure(
INSTALLED_APPS=["attendance"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
DEFAULT_AUTO_FIELD="django.db.models.BigAutoField",
)
django.setup()
from django.core.management import call_command
call_command("makemigrations", "attendance", verbosity=0)
print(sorted(p.name for p in (app / "migrations").glob("0*.py")))
call_command("showmigrations", "attendance")
call_command("migrate", "attendance", verbosity=0)
call_command("showmigrations", "attendance")
Standalone script. It writes a tiny app to a temporary folder, then calls makemigrations, showmigrations and migrate the same way manage.py would.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
['0001_initial.py']
attendance
[ ] 0001_initial
attendance
[X] 0001_initial
Key points
makemigrations writes files and does not touch the database
migrate runs unapplied files and records them in django_migrations
Migration files belong in version control
sqlmigrate shows the SQL before you run it
makemigrations --check catches missing migrations in CI
Common mistakes
Running migrate and expecting it to notice model changes without makemigrations
Deleting or editing migration files that already ran on production
Not committing migration files, so each server generates different ones
Ignoring a migration conflict instead of merging it
Follow-ups
How do you write a migration that changes data, not schema?
How would you roll back a bad migration?
What happens when two branches both add migration 0005?
Tips
Say clearly which command touches the database
Mention sqlmigrate for reviewing SQL
Add the CI check with --check to show production habits
5.django-0005Easyfresher
What is a QuerySet in Django, and what does it mean that QuerySets are lazy?
A QuerySet is a collection of rows described by a query, built with methods like filter(), exclude() and order_by(). It is lazy: building or chaining it runs no SQL. The query runs only when the results are needed, for example when you loop over it, slice with a step, call list(), len() or bool(), or print it.
Full answer
Student.objects is a Manager. Calling methods such as .all(), .filter(marks__gte=40), .exclude(...) or .order_by("-marks") on it returns a QuerySet. Each call returns a new QuerySet, so you can chain them.
Lazy means Django only builds a description of the SQL until it really needs data. These actions run the query (Django calls this "evaluating" the QuerySet):
iterating: for s in qs:
list(qs), len(qs), bool(qs) or if qs:
repr(qs) (what the shell shows)
slicing with a step, such as qs[::2]
Once evaluated, a QuerySet caches its rows. Looping over the same QuerySet twice uses the cache. But creating a new QuerySet (for example qs.filter(...) again) runs a new query.
Methods that run immediately and return something other than a QuerySet: get(), first(), count(), exists(), aggregate(), create(), update(), delete().
get() returns exactly one object. It raises DoesNotExist when there is none and MultipleObjectsReturned when there are several. first() returns None when empty.
Field lookups use a double underscore: name__icontains="an", marks__range=(40, 60), class_room__name="10A" (follows a relation).
Practical tip: use exists() to check if any row matches and count() for a number, instead of loading full objects with len(), unless you need the objects anyway.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.db import models, connection
from django.test.utils import CaptureQueriesContext
class Student(models.Model):
name = models.CharField(max_length=50)
marks = models.IntegerField()
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
editor.create_model(Student)
Student.objects.bulk_create([
Student(name="Asha", marks=91), Student(name="Ravi", marks=38), Student(name="Kiran", marks=67),
])
with CaptureQueriesContext(connection) as ctx:
passed = Student.objects.filter(marks__gte=40).order_by("-marks") # no SQL yet
print("queries after building:", len(ctx.captured_queries))
names = [s.name for s in passed] # runs SQL
again = [s.name for s in passed] # uses the cache
print("queries after two loops:", len(ctx.captured_queries))
print(names, again == names)
print(Student.objects.filter(marks__lt=40).exists(), Student.objects.count())
try:
Student.objects.get(marks__gte=40)
except Student.MultipleObjectsReturned:
print("get() found more than one row")
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
queries after building: 0
queries after two loops: 1
['Asha', 'Kiran'] True
True 3
get() found more than one row
Key points
QuerySets are built lazily and run on evaluation
Chaining returns new QuerySets
Evaluated QuerySets cache their results
get() raises DoesNotExist or MultipleObjectsReturned
Prefer exists() and count() when you do not need objects
Common mistakes
Thinking every chained call hits the database
Calling len(qs) only to get a count
Expecting a re-filtered QuerySet to reuse the earlier cache
Using get() where zero or many rows are possible without handling the exceptions
Follow-ups
What is the difference between qs.count() and len(qs)?
When does slicing a QuerySet run a query?
How would you see the SQL a QuerySet will run?
Tips
List three things that evaluate a QuerySet
Mention the result cache and when it is not reused
Show you know print(qs.query) for inspecting SQL
6.django-0006Easyfresher
How does URL routing work in Django? Explain path(), converters, include() and reverse().
Django matches the request path against urlpatterns in order. path() takes a route string, a view and an optional name; converters such as <int:pk> capture parts of the URL and pass them to the view as keyword arguments. include() mounts another URL list under a prefix, and reverse() builds a URL from its name so links do not break when routes change.
Full answer
The root URL list is set by ROOT_URLCONF, normally project/urls.py. Django walks urlpatterns from top to bottom and stops at the first match.
Built-in converters: str (default, no slash), int, slug, uuid, path (allows slashes). <int:pk> both checks that the segment is digits and converts it to a Python int before calling the view. If the segment is not a number, the pattern simply does not match, and Django moves on, which usually ends in a 404. You can register custom converters with register_converter.
re_path() uses regular expressions for cases converters cannot express.
include("library.urls") lets each app own its URLs. With app_name = "library" in the app's urls.py, names become namespaced: library:book-detail.
reverse("student-detail", kwargs={"pk": 7}) returns /students/7/. In templates, {% url 'student-detail' pk=7 %} does the same. Use names everywhere instead of hard-coding paths, so changing a route updates every link.
Trailing slashes: with APPEND_SLASH = True (the default) and CommonMiddleware, a GET to /students redirects to /students/ if only the slashed version exists.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.http import HttpResponse
from django.urls import path, reverse, resolve, include
def student_list(request):
return HttpResponse("all students")
def student_detail(request, pk):
return HttpResponse(f"student {pk} ({type(pk).__name__})")
def book_detail(request, slug):
return HttpResponse(f"book {slug}")
library_patterns = ([path("books/<slug:slug>/", book_detail, name="book-detail")], "library")
urlpatterns = [
path("students/", student_list, name="student-list"),
path("students/<int:pk>/", student_detail, name="student-detail"),
path("library/", include(library_patterns)),
]
settings.ROOT_URLCONF = __name__
print(reverse("student-detail", kwargs={"pk": 7}))
print(reverse("library:book-detail", kwargs={"slug": "wings-of-fire"}))
match = resolve("/students/42/")
print(match.view_name, match.kwargs)
print(match.func(None, **match.kwargs).content.decode())
from django.urls import Resolver404
try:
resolve("/students/abc/")
except Resolver404:
print("/students/abc/ does not match any pattern")
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
/students/7/
/library/books/wings-of-fire/
student-detail {'pk': 42}
student 42 (int)
/students/abc/ does not match any pattern
Key points
urlpatterns are checked in order; first match wins
Converters validate and convert captured values
include() and app_name give each app its own namespaced URLs
reverse() and {% url %} build links from names
Non-matching converters lead to a 404, not a crash
Common mistakes
Hard-coding URLs in templates instead of using {% url %}
Placing a broad pattern above a specific one so the specific one never matches
Expecting <int:pk> to give a string
Forgetting app_name and then getting NoReverseMatch with a namespaced name
Follow-ups
How would you write a custom path converter for a year like 2026?
What causes NoReverseMatch and how do you debug it?
When would you still use re_path()?
Tips
Mention that order matters in urlpatterns
Explain that converters do both validation and type conversion
Recommend reverse() and named URLs as a maintenance habit
7.django-0007Easyfresher
What is a function-based view in Django, and when do you use render(), HttpResponse, JsonResponse and redirect()?
A function-based view is a Python function that takes an HttpRequest and returns an HttpResponse. HttpResponse sends raw content, render() fills a template and returns HTML, JsonResponse serialises a dict to JSON with the right content type, and redirect() returns a 302 to another URL or named route.
Full answer
A view is any callable that takes a request and returns a response. The simplest kind is a plain function:
python
def hello(request):
return HttpResponse("Hello")
The request object carries everything about the call: request.method, request.GET (query string), request.POST (form data), request.headers, request.user (with auth middleware), request.COOKIES, request.FILES.
Ways to respond:
HttpResponse(content, status=200, content_type=...) for plain text or anything you build yourself.
render(request, "students/list.html", {"students": qs}) loads a template, fills it with context and returns an HttpResponse.
JsonResponse({"present": 28}) dumps the dict to JSON and sets Content-Type: application/json. To return a list, pass safe=False.
redirect("student-list") or redirect(obj) (calls obj.get_absolute_url()) returns a 302. Pass permanent=True for 301.
HttpResponseNotAllowed, HttpResponseBadRequest and friends for specific status codes, or raise Http404.
A common pattern for forms is "POST, then redirect, then GET" (Post/Redirect/Get). After a successful POST, redirect so a browser refresh does not submit the form again.
Function views are easy to read for small, one-off logic. Class-based views help when many views share the same shape.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
import json
from django.http import HttpResponse, JsonResponse
from django.shortcuts import redirect
from django.test import RequestFactory
from django.urls import path
from django.views.decorators.http import require_POST
def attendance_summary(request):
present = int(request.GET.get("present", 0))
return JsonResponse({"class": "10A", "present": present})
def roll_numbers(request):
return JsonResponse([1, 2, 3], safe=False)
@require_POST
def mark_present(request):
# ... save the attendance record here ...
return redirect("summary")
urlpatterns = [path("summary/", attendance_summary, name="summary")]
settings.ROOT_URLCONF = __name__
rf = RequestFactory()
r1 = attendance_summary(rf.get("/summary/", {"present": "28"}))
print(r1.status_code, r1["Content-Type"], json.loads(r1.content))
print(roll_numbers(rf.get("/")).content.decode())
r2 = mark_present(rf.post("/mark/"))
print(r2.status_code, r2["Location"])
print(mark_present(rf.get("/mark/")).status_code) # GET is not allowed
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
200 application/json {'class': '10A', 'present': 28}
[1, 2, 3]
302 /summary/
405
Key points
A view takes HttpRequest and returns HttpResponse
render() = template + context -> HttpResponse
JsonResponse needs safe=False for non-dict data
Redirect after a successful POST
Decorators like require_POST restrict methods
Common mistakes
Returning a dict from a view instead of a response object
Passing a list to JsonResponse without safe=False
Rendering a page directly after POST, which causes double submits on refresh
Reading request.POST for JSON bodies (use json.loads(request.body))
Follow-ups
How do you read a JSON request body in a plain Django view?
What does the Post/Redirect/Get pattern prevent?
When would you switch to a class-based view?
Tips
Mention request.GET vs request.POST vs request.body
Explain safe=False rather than just using it
Bring up Post/Redirect/Get for form handling
8.django-0008Easyfresher
How do Django templates work? Explain variables, filters, tags, template inheritance and auto-escaping.
Django templates use {{ variable }} to print values, filters like {{ name|upper }} to transform them, and tags like {% for %} and {% if %} for logic. Inheritance lets a base.html define {% block %} sections that child templates fill with {% extends %}. Output is HTML-escaped by default, which blocks most XSS.
Full answer
The Django Template Language (DTL) is deliberately limited. It shows data; it does not run arbitrary Python. Heavy logic belongs in views or models.
Building blocks:
Variables: {{ student.name }}. The dot tries a dictionary key, then an attribute, then a list index. A callable with no arguments is called. Missing values print as an empty string (controlled by string_if_invalid).
Filters: {{ marks|default:"absent" }}, {{ name|title }}, {{ fee|floatformat:2 }}, {{ joined|date:"d M Y" }}, {{ items|length }}. Filters chain left to right.
Tags: {% if %}, {% for s in students %}...{% empty %}...{% endfor %}, {% url 'name' %}, {% csrf_token %}, {% include "row.html" %}, {% with %}.
Comments: {# short #} and {% comment %}...{% endcomment %}.
Inheritance avoids copying the same header and footer into every page. base.html defines blocks:
A child starts with {% extends "base.html" %} and overrides only the blocks it needs. {{ block.super }} keeps the parent's content and adds to it.
Auto-escaping turns <, >, &, quotes into HTML entities, so a student named <script> shows as text and does not run. Only switch escaping off with |safe or mark_safe() for content you created or sanitised yourself.
Templates are found through the TEMPLATES setting: DIRS for project-level folders and APP_DIRS=True for each app's templates/ folder. Namespacing as templates/students/list.html avoids two apps clashing on list.html.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.template import engines
settings.TEMPLATES = [{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"OPTIONS": {"loaders": [("django.template.loaders.locmem.Loader", {
"base.html": "<h1>{% block title %}College{% endblock %}</h1>{% block content %}{% endblock %}",
"results.html": (
"{% extends 'base.html' %}"
"{% block title %}{{ block.super }} results{% endblock %}"
"{% block content %}<ul>{% for s in students %}"
"<li>{{ s.name|title }}: {{ s.marks|default:'absent' }}</li>"
"{% empty %}<li>No students</li>{% endfor %}</ul>{% endblock %}"
),
})]},
}]
django_engine = engines["django"]
html = django_engine.get_template("results.html").render({
"students": [
{"name": "asha rao", "marks": 91},
{"name": "<script>alert(1)</script>", "marks": None},
]
})
print(html)
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
<h1>College results</h1><ul><li>Asha Rao: 91</li><li><Script>Alert(1)</Script>: absent</li></ul>
Key points
{{ }} prints, |filters transform, {% %} tags control flow
{% extends %} and {% block %} give layout reuse
Auto-escaping is on by default and prevents XSS
Only use |safe on trusted content
Keep business logic out of templates
Common mistakes
Writing complex logic in templates instead of preparing data in the view
Marking user input as safe
Copy-pasting header HTML into every template instead of using inheritance
Putting all templates in a flat folder so two apps clash on the same file name
Follow-ups
How do you write a custom template filter?
What is a context processor?
How is {% include %} different from {% extends %}?
Tips
Show a tiny base/child example from memory
Say that auto-escaping is on by default and what it protects against
Mention that DTL limits logic on purpose
9.django-0009Easyfresher
What is the difference between a Django Form and a ModelForm, and how does form validation work?
A Form declares its fields by hand; a ModelForm builds its fields from a model and can save an instance. Calling is_valid() runs each field's to_python and validators, then clean_<field>() methods, then clean() for cross-field rules. Valid data ends up in cleaned_data and errors in form.errors.
Full answer
Forms turn untrusted input (usually request.POST) into clean Python values and readable error messages.
forms.Form is for input that does not map directly to one model, such as a search box or a contact form. You declare each field yourself.
forms.ModelForm reads fields from a model:
python
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ["name", "marks"]
It copies field types, max_length, choices and blank rules, and adds form.save() which creates or updates the instance. Always list fields explicitly; fields = "__all__" can expose fields you add later, such as is_admin.
Validation order when you call form.is_valid():
For each field: to_python() converts the string ("85" to 85), then field validators run.
clean_<fieldname>() runs for extra rules on one field. It must return the cleaned value.
clean() runs once for rules involving several fields. Use self.add_error(field, msg) or raise ValidationError.
For ModelForm, model validation (full_clean on the instance, including unique checks) runs too.
Results: form.cleaned_data holds valid values, form.errors holds messages per field, and form.non_field_errors() holds errors from clean().
Typical view: if POST and valid, save and redirect; otherwise render the form again with errors. form.save(commit=False) returns an unsaved instance so you can set extra fields (like the logged-in teacher) before saving.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django import forms
from django.db import models, connection
class Student(models.Model):
name = models.CharField(max_length=30)
marks = models.IntegerField()
max_marks = models.IntegerField(default=100)
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
editor.create_model(Student)
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ["name", "marks", "max_marks"]
def clean_name(self):
return self.cleaned_data["name"].strip().title()
def clean(self):
data = super().clean()
if data.get("marks") is not None and data.get("max_marks") and data["marks"] > data["max_marks"]:
self.add_error("marks", "Marks cannot be more than max marks.")
return data
good = StudentForm({"name": " neha singh ", "marks": "88", "max_marks": "100"})
print(good.is_valid(), good.cleaned_data)
saved = good.save()
print(saved.pk, saved.name)
bad = StudentForm({"name": "Arjun", "marks": "120", "max_marks": "100"})
print(bad.is_valid(), bad.errors.get_json_data())
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
True {'name': 'Neha Singh', 'marks': 88, 'max_marks': 100}
1 Neha Singh
False {'marks': [{'message': 'Marks cannot be more than max marks.', 'code': ''}]}
Key points
Form = fields by hand, ModelForm = fields from a model + save()
cleaned_data has typed values; errors has messages
List fields explicitly in ModelForm Meta
save(commit=False) lets you set extra fields first
Common mistakes
Using fields = '__all__' and exposing sensitive fields
Forgetting to return the value from clean_<field>()
Reading request.POST directly after validation instead of cleaned_data
Rendering a success page on POST instead of redirecting
Follow-ups
How do you show a form with initial values for editing an existing record?
Where would you validate that a roll number is unique per class?
What are formsets used for?
Tips
Recite the validation order, it is a favourite follow-up
Mention commit=False with a concrete reason
Point out the security issue with __all__
10.django-0010Easyfresher
How do you register a model in the Django admin and customise how it looks?
Register a model with admin.site.register() or the @admin.register decorator, usually with a ModelAdmin subclass. ModelAdmin options such as list_display, list_filter, search_fields, ordering, readonly_fields and list_select_related control the change list and edit form. The admin is meant for trusted staff, not as a public front end.
Full answer
The admin (django.contrib.admin) reads your models and builds list, add, edit and delete pages for staff users. It needs auth, contenttypes, sessions and messages in INSTALLED_APPS and a URL such as path("admin/", admin.site.urls). Create a login with python manage.py createsuperuser.
list_display picks columns. It can include model methods or ModelAdmin methods, which you can label with the @admin.display(description=..., boolean=True) decorator.
list_filter adds a sidebar filter; search_fields adds a search box (author__name searches across a relation).
ordering, list_per_page, date_hierarchy.
readonly_fields, fields or fieldsets shape the edit form.
inlines edit child rows (for example TabularInline for book copies) on the parent's page.
list_select_related or get_queryset() with select_related avoids one query per row when a column shows a foreign key.
actions add bulk operations, like "mark selected books as lost".
Permissions come from the auth app: each model gets add, change, delete and view permissions, and staff users see only what they are allowed to.
The admin is an internal tool. Customer-facing pages should be normal views, because the admin's layout, URLs and permission model are built for staff.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "django.contrib.admin",
"django.contrib.sessions", "django.contrib.messages", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.contrib import admin
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=80)
author = models.CharField(max_length=60)
copies = models.PositiveIntegerField(default=1)
class Meta:
app_label = "school"
def __str__(self):
return self.title
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ["title", "author", "copies", "is_available"]
list_filter = ["author"]
search_fields = ["title", "author"]
ordering = ["title"]
@admin.display(boolean=True, description="Available?")
def is_available(self, obj):
return obj.copies > 0
print(admin.site.is_registered(Book))
model_admin = admin.site._registry[Book]
print(model_admin.list_display, model_admin.search_fields)
print(model_admin.is_available(Book(title="Godan", author="Premchand", copies=0)))
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. The snippet inspects the registered ModelAdmin instead of starting a server.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
True
['title', 'author', 'copies', 'is_available'] ['title', 'author']
False
Key points
Register with @admin.register and a ModelAdmin
list_display, list_filter, search_fields shape the list page
Inlines edit related rows on the parent page
Use list_select_related to avoid N+1 in the admin list
Admin is for staff, not public users
Common mistakes
Using the admin as the public user interface
Showing a foreign key column without list_select_related and getting one query per row
Giving every staff user superuser rights instead of using permissions
Leaving the admin at /admin/ with no rate limiting or 2FA on a public site
Follow-ups
How would you add a bulk action to the admin?
How can you restrict which rows a staff user sees in the admin?
How do inlines work for a one-to-many relation?
Tips
Name four ModelAdmin options with what each does
Mention the N+1 risk in list_display
Say clearly that the admin is for internal staff
11.django-0011Easyfresher
What does on_delete do on a Django ForeignKey, and when would you use CASCADE, PROTECT, SET_NULL or RESTRICT?
on_delete tells Django what to do with child rows when the parent row they point to is deleted. CASCADE deletes the children too, PROTECT blocks the delete by raising ProtectedError, SET_NULL sets the foreign key to NULL (needs null=True), SET_DEFAULT uses the field default, and RESTRICT blocks unless the children are being deleted through another cascade.
Full answer
A ForeignKey creates a many-to-one link: many Marks rows can point to one Student. on_delete is required and decides what happens to those Marks when the Student is deleted.
Options:
CASCADE: delete the children as well. Good when a child has no meaning without the parent, such as order lines without an order.
PROTECT: refuse to delete the parent while children exist, raising ProtectedError. Good for reference data, such as a Course that still has enrolled students.
SET_NULL: keep the child and set the link to NULL. The field needs null=True. Good for "the teacher left but keep the class record".
SET_DEFAULT / SET(value_or_callable): point to a default or a computed value.
RESTRICT (Django 3.1+): like PROTECT, but allows the delete if the child is also being removed through a CASCADE from another path.
DO_NOTHING: Django does nothing; the database decides, which usually means an integrity error.
Django emulates these rules in Python, not with database ON DELETE clauses. It collects related objects, fires pre_delete/post_delete signals, and deletes in the right order. That has two effects: deleting one parent with many children can run many queries, and raw SQL deletes that bypass the ORM do not cascade. Django 6.1 (August 2026) adds database-level options, DB_CASCADE, DB_SET_NULL and DB_SET_DEFAULT, which use the SQL ON DELETE clause and skip loading the child objects; DB_CASCADE does not send delete signals.
related_name sets the reverse accessor: student.marks.all() instead of student.marks_set.all().
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.db import models, connection
from django.db.models import ProtectedError
class Course(models.Model):
name = models.CharField(max_length=40)
class Meta:
app_label = "school"
class Teacher(models.Model):
name = models.CharField(max_length=40)
class Meta:
app_label = "school"
class Student(models.Model):
name = models.CharField(max_length=40)
course = models.ForeignKey(Course, on_delete=models.PROTECT, related_name="students")
mentor = models.ForeignKey(Teacher, on_delete=models.SET_NULL, null=True, related_name="mentees")
class Meta:
app_label = "school"
class Marks(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="marks")
score = models.IntegerField()
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
for m in (Course, Teacher, Student, Marks):
editor.create_model(m)
bca = Course.objects.create(name="BCA")
mentor = Teacher.objects.create(name="Mr. Iyer")
s = Student.objects.create(name="Farah", course=bca, mentor=mentor)
Marks.objects.create(student=s, score=72)
mentor.delete()
s.refresh_from_db()
print("mentor after SET_NULL:", s.mentor)
try:
bca.delete()
except ProtectedError:
print("PROTECT stopped deleting a course that has students")
print(s.delete()) # CASCADE removes the marks too
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
mentor after SET_NULL: None
PROTECT stopped deleting a course that has students
(2, {'school.Marks': 1, 'school.Student': 1})
Key points
on_delete runs when the parent row is deleted
CASCADE removes children; PROTECT and RESTRICT block deletes
SET_NULL needs null=True
Django emulates on_delete in Python, not in the database
related_name names the reverse accessor
Common mistakes
Using CASCADE on reference data and wiping out history by deleting one row
Using SET_NULL without null=True, which fails at system check time
Assuming raw SQL deletes follow on_delete rules
Not setting related_name and getting confusing _set accessors or clashes
Follow-ups
Why might deleting one user with CASCADE be slow?
What is the difference between PROTECT and RESTRICT?
How would you implement soft delete instead of a real delete?
Tips
Pair each option with a real-world example
Mention that Django emulates cascades in Python
Bring up soft delete for records that must be kept for audit
12.django-0012Easyfresher
What is the difference between static files and media files in Django, and how are they served in production?
Static files are assets you ship with the code, such as CSS, JavaScript and logos. Media files are uploaded by users at runtime, such as profile photos. Static files are gathered with collectstatic into STATIC_ROOT and served by the web server, WhiteNoise or a CDN; media files go to MEDIA_ROOT or object storage and need their own serving and security rules.
Full answer
Both are files, but they have different owners and life cycles.
Static files belong to the code. You put them in each app's static/ folder or in STATICFILES_DIRS. Settings involved:
STATIC_URL = "static/": the URL prefix.
STATIC_ROOT: the folder where python manage.py collectstatic copies every static file from every app.
In templates: {% load static %} then {% static 'css/site.css' %}.
With DEBUG=True, runserver serves static files for you. In production Django does not. Use the web server (Nginx), WhiteNoise (a middleware that serves files from Python with caching headers) or a CDN. ManifestStaticFilesStorage (set through the STORAGES setting in Django 4.2+) adds a content hash to file names like site.3f2a1b.css, so browsers can cache them for a long time and still get new versions after a deploy.
Media files are user uploads, handled by FileField and ImageField.
MEDIA_URL and MEDIA_ROOT set the URL and folder for local storage.
In production, store them in object storage (Amazon S3, Google Cloud Storage, Azure Blob) through django-storages, because app servers come and go and local disks are not shared.
Treat uploads as untrusted: validate size and type, never serve user-uploaded HTML from your main domain, and use signed or private URLs for private files such as fee receipts.
The model field stores only the file path in the database, not the file bytes.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
import tempfile
from pathlib import Path
from django.core.files.base import ContentFile
from django.core.files.storage import FileSystemStorage
from django.template import Engine, Context
media_root = Path(tempfile.mkdtemp())
settings.STATIC_URL = "/static/"
settings.MEDIA_URL = "/media/"
# Media: a user upload saved through a storage backend
storage = FileSystemStorage(location=media_root, base_url=settings.MEDIA_URL)
name = storage.save("receipts/fee-2026.txt", ContentFile(b"Fee paid: 1200"))
print(name, storage.url(name), storage.size(name))
# Static: a URL built by the {% static %} tag
engine = Engine(libraries={"static": "django.templatetags.static"})
html = engine.from_string("{% load static %}<link href=\"{% static 'css/site.css' %}\">").render(Context())
print(html)
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
receipts/fee-2026.txt /media/receipts/fee-2026.txt 14
<link href="/static/css/site.css">
Key points
Static = shipped with code; media = uploaded by users
collectstatic copies static files into STATIC_ROOT
Django does not serve static files in production by itself
Hashed file names allow long browser caching
Store media in object storage and treat uploads as untrusted
Common mistakes
Serving static files through Django in production with DEBUG=True left on
Saving uploads on the local disk of a server that is replaced on each deploy
Trusting the uploaded file name or extension
Forgetting to run collectstatic in the deployment pipeline
Follow-ups
Why do hashed static file names help caching?
How would you serve private media files such as ID cards?
What does WhiteNoise do and when is it enough?
Tips
Define each type with an example
Name one production serving option for each
Mention upload validation as a security point
13.django-0013Easyfresher
What is CSRF, and how does Django protect against it?
CSRF (cross-site request forgery) tricks a logged-in user's browser into sending an unwanted request, using the cookies the browser attaches automatically. Django's CsrfViewMiddleware requires a secret token on unsafe requests (POST, PUT, PATCH, DELETE); forms include it with {% csrf_token %} and JavaScript sends it in the X-CSRFToken header. Requests without a matching token get 403.
Full answer
Imagine a student is logged in to the college portal. They open another site that contains a hidden form posting to portal.example/fees/transfer/. The browser sends the portal's session cookie with that request automatically, so without protection the portal would think the student made it. That is cross-site request forgery.
Django's defence is django.middleware.csrf.CsrfViewMiddleware, enabled by default:
Django sets a csrftoken cookie.
Every form that posts back must include the token, which {% csrf_token %} renders as a hidden input.
For POST, PUT, PATCH and DELETE, the middleware compares the submitted token with the cookie. A missing or wrong token returns 403 Forbidden.
For HTTPS requests it also checks the Origin (or Referer) header against the host and CSRF_TRUSTED_ORIGINS.
The attacker's site cannot read the cookie or the page because of the browser's same-origin policy, so it cannot supply the right token.
For JavaScript calls, read the token (from the cookie or a rendered value) and send it in the X-CSRFToken header.
Rules worth knowing:
GET requests must not change data. CSRF checks skip safe methods.
@csrf_exempt turns protection off for a view. Use it only for endpoints that authenticate without cookies, such as webhooks verified by a signature.
SameSite=Lax cookies (Django's default) add a second layer but do not replace tokens.
In DRF, SessionAuthentication enforces CSRF; token or JWT authentication in a header does not need it, because browsers do not attach headers automatically.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.http import HttpResponse
from django.middleware.csrf import get_token
from django.test import Client
from django.urls import path
from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def form_page(request):
return HttpResponse(f'<input name="csrfmiddlewaretoken" value="{get_token(request)}">')
def pay_fee(request):
return HttpResponse("payment recorded")
urlpatterns = [path("form/", form_page), path("pay/", pay_fee)]
settings.ROOT_URLCONF = __name__
settings.MIDDLEWARE = ["django.middleware.csrf.CsrfViewMiddleware"]
client = Client(enforce_csrf_checks=True)
print("POST without token:", client.post("/pay/").status_code)
client.get("/form/")
token = client.cookies["csrftoken"].value
print("POST with token:", client.post("/pay/", {"csrfmiddlewaretoken": token}).status_code)
print("Header token:", client.post("/pay/", HTTP_X_CSRFTOKEN=token).status_code)
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. The test Client normally skips CSRF checks; enforce_csrf_checks=True turns them on.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
POST without token: 403
POST with token: 200
Header token: 200
Key points
CSRF abuses cookies that browsers send automatically
CsrfViewMiddleware checks a token on unsafe methods
Use {% csrf_token %} in forms and X-CSRFToken in JavaScript
Never change data on GET
csrf_exempt only for non-cookie-authenticated endpoints
Common mistakes
Adding @csrf_exempt to make a form 'work' instead of including the token
Changing data in a GET view
Thinking CSRF protects against XSS; an XSS bug can read the token
Assuming token-in-header APIs need CSRF tokens too
Follow-ups
Why does a JWT sent in the Authorization header not need CSRF protection?
What does SameSite=Lax change?
When is csrf_exempt acceptable?
Tips
Explain the attack with a concrete scenario before the defence
Mention both the form field and the header
Link CSRF to cookie-based auth specifically
14.django-0014Easyfresher
What do DEBUG, ALLOWED_HOSTS and SECRET_KEY do in Django settings, and how should they be set in production?
DEBUG=True shows detailed error pages and must be False in production. ALLOWED_HOSTS lists the host names the site will answer to, which blocks Host header attacks. SECRET_KEY signs sessions, password reset tokens and other signed data; it must be long, random and kept out of version control, usually loaded from an environment variable.
Full answer
These three settings cause many real production incidents.
DEBUG
With DEBUG=True, an unhandled error shows a page with the stack trace, local variables and settings (with some values hidden). That is useful locally and dangerous in public.
With DEBUG=False, Django shows a plain 500 page (or your 500.html) and emails or logs the error through LOGGING/ADMINS.
DEBUG also changes behaviour: runserver stops serving static files, and SQL queries are no longer recorded in connection.queries.
ALLOWED_HOSTS
A list such as ["portal.example.edu", ".example.edu"] (a leading dot allows subdomains).
Django validates the request's Host header against it whenever request.get_host() is called, which CommonMiddleware, CSRF checks and URL building all do, and returns 400 for other hosts. This stops attackers from making Django build links (password reset emails, absolute URLs) with a host they control.
When DEBUG=True and the list is empty, Django allows localhost names only.
SECRET_KEY
Used for signing: sessions with signed cookies, password reset tokens, django.core.signing, messages.
If it leaks, attackers can forge signed data. If you change it, existing sessions and reset links become invalid. Django 4.1+ supports SECRET_KEY_FALLBACKS for rotating keys without logging everyone out.
Load secrets from the environment (os.environ["DJANGO_SECRET_KEY"]) or a secrets manager, not from settings.py in Git. python manage.py check --deploy warns about insecure values.
python
import os
os.environ.setdefault("DJANGO_SECRET_KEY", "x7#k2-demo-only-not-for-production-0c9f1e5b8a7d6c4e3f2a1b")
os.environ.setdefault("DJANGO_ALLOWED_HOSTS", "portal.example.edu")
import django
from django.conf import settings
settings.configure(
DEBUG=os.environ.get("DJANGO_DEBUG", "0") == "1",
SECRET_KEY=os.environ["DJANGO_SECRET_KEY"],
ALLOWED_HOSTS=os.environ["DJANGO_ALLOWED_HOSTS"].split(","),
ROOT_URLCONF=__name__,
MIDDLEWARE=["django.middleware.common.CommonMiddleware"],
INSTALLED_APPS=[],
)
django.setup()
from django.core import signing
from django.http import HttpResponse
from django.test import Client
from django.urls import path
urlpatterns = [path("", lambda r: HttpResponse("home"))]
print("DEBUG:", settings.DEBUG)
c = Client()
print("good host:", c.get("/", HTTP_HOST="portal.example.edu").status_code)
print("bad host:", c.get("/", HTTP_HOST="evil.example").status_code)
token = signing.dumps({"student": 7})
print("signed data round trip:", signing.loads(token))
try:
signing.loads(token[:-2] + "xx")
except signing.BadSignature:
print("tampered token rejected")
Standalone script. It reads settings from environment variables the way a production settings.py should. The demo key is for this example only. Django logs a 'DisallowedHost' warning to stderr for the bad host, which is expected.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
DEBUG: False
good host: 200
bad host: 400
signed data round trip: {'student': 7}
tampered token rejected
Key points
DEBUG must be False in production
ALLOWED_HOSTS validates the Host header
SECRET_KEY signs sessions and tokens; keep it secret
SECRET_KEY_FALLBACKS allows key rotation
check --deploy flags unsafe settings
Common mistakes
Deploying with DEBUG=True
Setting ALLOWED_HOSTS = ['*'] in production
Committing SECRET_KEY to a public repository
Rotating SECRET_KEY without SECRET_KEY_FALLBACKS and logging every user out
Follow-ups
What would an attacker do with a leaked SECRET_KEY?
How do you manage different settings for local, staging and production?
What else does check --deploy warn about?
Tips
Explain the risk of each setting, not just its purpose
Mention environment variables or a secrets manager
Bring up manage.py check --deploy
15.django-0015Easyfresher
How does user authentication work in Django? Explain authenticate(), login(), logout() and login_required.
django.contrib.auth provides a User model, password hashing, sessions and permissions. authenticate() checks credentials against the configured backends and returns a user or None, login() stores the user's ID in the session, logout() clears the session, and @login_required (or LoginRequiredMixin) redirects anonymous users to LOGIN_URL.
Full answer
Django's auth system answers two questions: who are you (authentication) and what may you do (authorisation, through permissions and groups).
Main parts:
User model with username, password (a hash, never plain text), email, is_active, is_staff, is_superuser.
Password hashing with PBKDF2 by default; Argon2 and bcrypt are available. user.set_password() hashes; user.check_password() verifies.
AuthenticationMiddleware puts request.user on every request. Anonymous visitors get an AnonymousUser.
Sessions (SessionMiddleware) remember the logged-in user between requests through a cookie that holds only a session key.
The login steps:
user = authenticate(request, username=..., password=...) asks each backend in AUTHENTICATION_BACKENDS. It returns the user, or None if the details are wrong or the user is inactive.
login(request, user) saves the user ID in the session and rotates the session key, which prevents session fixation.
logout(request) flushes the session.
Protecting views:
@login_required for function views, LoginRequiredMixin for class views. Anonymous users are redirected to settings.LOGIN_URL with ?next=/original/path/.
@permission_required("library.add_book") or user.has_perm() for permissions.
Django 5.1 added LoginRequiredMiddleware, which protects every view by default; mark public ones with @login_not_required.
Django also ships ready views: LoginView, LogoutView (POST only since Django 5.0), and the password reset and change views.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "django.contrib.sessions", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.contrib.auth import authenticate, get_user_model, login
from django.contrib.auth.decorators import login_required
from django.core.management import call_command
from django.http import HttpResponse
from django.test import Client
from django.urls import path
settings.MIDDLEWARE = [
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
]
settings.ROOT_URLCONF = __name__
settings.LOGIN_URL = "/login/"
settings.PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"] # fast, for this demo only
call_command("migrate", verbosity=0)
User = get_user_model()
User.objects.create_user("priya", password="Chai-at-4pm")
@login_required
def my_marks(request):
return HttpResponse(f"Marks for {request.user.username}")
def login_view(request):
user = authenticate(request, username=request.POST["u"], password=request.POST["p"])
if user is None:
return HttpResponse("wrong details", status=401)
login(request, user)
return HttpResponse("logged in")
urlpatterns = [path("marks/", my_marks), path("login/", login_view)]
c = Client()
r = c.get("/marks/")
print(r.status_code, r["Location"])
print(c.post("/login/", {"u": "priya", "p": "wrong"}).status_code)
print(c.post("/login/", {"u": "priya", "p": "Chai-at-4pm"}).content.decode())
print(c.get("/marks/").content.decode())
print(User.objects.get(username="priya").password.split("$")[0])
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. MD5 hashing is used only to make the demo fast; keep the default hashers in real projects.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
302 /login/?next=/marks/
401
logged in
Marks for priya
md5
Key points
Passwords are stored as salted hashes
authenticate() checks; login() starts the session
request.user comes from AuthenticationMiddleware
login_required redirects to LOGIN_URL with ?next=
Django 5.1 adds LoginRequiredMiddleware
Common mistakes
Storing or comparing plain-text passwords
Calling login() without authenticate() first
Checking request.user.is_authenticated in templates but not protecting the view
Using a GET link for logout (Django 5.0 LogoutView requires POST)
Follow-ups
How would you let users log in with email instead of username?
What is session fixation and how does login() prevent it?
How do groups and permissions work together?
Tips
Separate authentication from authorisation in your answer
Mention password hashing and set_password()
Note the Django 5.x changes: POST-only logout and LoginRequiredMiddleware
16.django-0016Easyfresher
What does get_object_or_404 do, and why is it preferred over Model.objects.get() in views?
get_object_or_404(Model_or_queryset, **lookups) calls get() and turns DoesNotExist into Http404, so a missing record gives the visitor a 404 page instead of a 500 error. It accepts a QuerySet, which lets you scope lookups, for example to objects owned by the current user. get_list_or_404 does the same for filter() results that are empty.
Full answer
In a view such as /books/42/, the ID comes from the visitor. If book 42 does not exist, Book.objects.get(pk=42) raises Book.DoesNotExist. An unhandled exception becomes a 500 Internal Server Error, which is wrong: the server is fine, the resource is missing.
get_object_or_404 fixes that in one line:
python
book = get_object_or_404(Book, pk=pk)
Under the hood it calls queryset.get(**kwargs) and catches DoesNotExist, raising Http404 instead. Django's handler turns Http404 into a 404 response (your 404.html when DEBUG=False). It does not catch MultipleObjectsReturned, so use unique lookups.
Pass a QuerySet to add conditions:
python
book = get_object_or_404(Book.objects.filter(is_published=True), slug=slug)
loan = get_object_or_404(Loan, pk=pk, member=request.user)
The second line is an important security habit. Scoping by owner stops one member from reading another's loan by changing the ID in the URL (an insecure direct object reference, or IDOR). Returning 404 rather than 403 also avoids confirming that the record exists.
There is an async version for async views: aget_object_or_404 (Django 5.0+).
Keep it in views. In service functions that are not tied to HTTP, raise or handle DoesNotExist directly, because Http404 is an HTTP concept.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.db import models, connection
from django.http import Http404
from django.shortcuts import get_object_or_404
class Loan(models.Model):
member = models.CharField(max_length=30)
book = models.CharField(max_length=60)
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
editor.create_model(Loan)
Loan.objects.create(member="anil", book="Malgudi Days")
Loan.objects.create(member="sara", book="The Guide")
print(get_object_or_404(Loan, pk=1).book)
for who, pk in [("anil", 99), ("anil", 2)]:
try:
get_object_or_404(Loan, pk=pk, member=who)
except Http404 as exc:
print(f"{who} asking for loan {pk}: 404 ({exc})")
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
Malgudi Days
anil asking for loan 99: 404 (No Loan matches the given query.)
anil asking for loan 2: 404 (No Loan matches the given query.)
Key points
Turns DoesNotExist into Http404, so visitors see 404, not 500
Accepts a model, manager or QuerySet
Scope by owner to prevent IDOR
MultipleObjectsReturned is not caught
aget_object_or_404 exists for async views (Django 5.0+)
Common mistakes
Using objects.get() in views and returning 500 for bad IDs
Looking up by ID only, so users can read other users' records
Expecting it to handle MultipleObjectsReturned
Raising Http404 inside non-HTTP service code
Follow-ups
What is an IDOR vulnerability?
How do you customise the 404 page?
When would 403 be better than 404?
Tips
Say why a missing record is a 404 and not a 500
Show the owner-scoped version, it signals security awareness
Mention the async variant for Django 5
17.django-0017Easyfresher
How do you write tests in Django using TestCase and the test Client?
Subclass django.test.TestCase, put setup data in setUpTestData or setUp, and write test_ methods with assertions. Each test runs inside a transaction that is rolled back, so tests do not affect each other. self.client sends fake requests through URLs, middleware and views, and helpers like assertContains, assertRedirects and assertNumQueries check the result. Run with python manage.py test.
Full answer
Django's test tools build on Python's unittest.
django.test.TestCase:
Creates a separate test database (named test_<name>) before the run and destroys it after.
Wraps each test method in a transaction and rolls it back, so data created in one test never leaks into the next. This is fast.
setUpTestData(cls) runs once per class for shared read-only data; setUp(self) runs before every test.
The test Client (self.client) acts like a browser without a server:
self.client.force_login(user) skips the login form.
The response has status_code, content, context (template context) and templates.
Helpful assertions:
assertContains(response, "Wings of Fire"), assertNotContains
assertRedirects(response, "/login/?next=/books/")
assertTemplateUsed(response, "books/list.html")
assertNumQueries(2) as a context manager, to catch N+1 problems early
assertFormError for form errors
Other tools: RequestFactory builds requests for calling a view function directly (no middleware), SimpleTestCase for tests that need no database, TransactionTestCase when code depends on real commits (for example on_commit hooks).
Run with python manage.py test or with pytest plus pytest-django. A healthy test checks one behaviour, sets up only the data it needs and reads clearly as "given, when, then".
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
import unittest
from django.db import models, connection
from django.http import HttpResponse
from django.test import TestCase
from django.test.utils import setup_test_environment
from django.urls import path
class Book(models.Model):
title = models.CharField(max_length=60)
class Meta:
app_label = "school"
def book_list(request):
titles = ", ".join(Book.objects.order_by("title").values_list("title", flat=True))
return HttpResponse(titles or "No books")
urlpatterns = [path("books/", book_list)]
settings.ROOT_URLCONF = __name__
with connection.schema_editor() as editor:
editor.create_model(Book)
class BookListTests(TestCase):
@classmethod
def setUpTestData(cls):
Book.objects.create(title="Wings of Fire")
def test_lists_titles(self):
response = self.client.get("/books/")
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Wings of Fire")
def test_one_query(self):
with self.assertNumQueries(1):
self.client.get("/books/")
def test_data_is_rolled_back(self):
Book.objects.create(title="Gitanjali")
self.assertEqual(Book.objects.count(), 2)
def test_count_is_back_to_one(self):
self.assertEqual(Book.objects.count(), 1)
setup_test_environment()
suite = unittest.defaultTestLoader.loadTestsFromTestCase(BookListTests)
result = unittest.TextTestRunner(verbosity=0, stream=open("/dev/null", "w")).run(suite)
print("ran:", result.testsRun, "failures:", len(result.failures), "errors:", len(result.errors))
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Normally you run tests with `python manage.py test`; this script runs the TestCase through unittest directly.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
ran: 4 failures: 0 errors: 0
Key points
TestCase wraps each test in a rolled-back transaction
setUpTestData for shared data, setUp per test
self.client runs URLs, middleware and views
assertNumQueries catches N+1 regressions
RequestFactory calls a view without middleware
Common mistakes
Using unittest.TestCase so the database is not reset between tests
Creating heavy data in setUp when setUpTestData would run it once
Testing on_commit callbacks inside TestCase without captureOnCommitCallbacks
Asserting only status codes and not the content
Follow-ups
When do you need TransactionTestCase?
How do you test a view that requires login?
How would you test that an email was sent?
Tips
Explain the rollback behaviour, it is the key idea
Mention assertNumQueries as a performance guard
Know both manage.py test and pytest-django
18.django-0018Mediummid
What is the N+1 query problem in Django, and how do select_related and prefetch_related fix it?
N+1 happens when one query loads a list and then each item triggers another query for a related object. select_related follows ForeignKey and OneToOne links with a SQL JOIN in the same query. prefetch_related runs one extra query per relation for many-valued links (reverse ForeignKey, ManyToMany) and joins the results in Python. Prefetch objects let you filter or order the prefetched rows.
Full answer
Accessing a related object on a model instance runs a query the first time. In a loop that becomes one query for the list plus one per row:
python
for s in Student.objects.all(): # 1 query
print(s.class_room.name) # +1 query per student
With 500 students that is 501 queries. Each is fast alone, but the round trips add up and the page gets slow under load.
select_related("class_room") adds a SQL JOIN so the class room comes back in the same row. It works for forward ForeignKey and OneToOneField (and reverse OneToOne), and can follow chains: select_related("class_room__school").
prefetch_related("marks") is for relations that return many objects per row: reverse ForeignKey (student.marks) and ManyToMany. A JOIN there would repeat each student once per mark, so Django instead runs a second query (WHERE student_id IN (...)) and stitches results together in Python. Total: 2 queries no matter how many students.
Prefetch("marks", queryset=Mark.objects.filter(score__gte=70), to_attr="good_marks") customises the second query and stores the result in a list attribute.
Things that silently undo a prefetch: calling .filter() on the related manager inside the loop (s.marks.filter(...)) creates a new query each time. Filter in the Prefetch queryset instead.
How to find N+1: Django Debug Toolbar, assertNumQueries in tests, CaptureQueriesContext, or logging django.db.backends in development. Django 5.x has no automatic fix, so make query counts part of tests for list pages and API endpoints.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.db import models, connection
from django.test.utils import CaptureQueriesContext
class ClassRoom(models.Model):
name = models.CharField(max_length=10)
class Meta:
app_label = "school"
class Student(models.Model):
name = models.CharField(max_length=40)
class_room = models.ForeignKey(ClassRoom, on_delete=models.CASCADE, related_name="students")
class Meta:
app_label = "school"
class Mark(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="marks")
subject = models.CharField(max_length=20)
score = models.IntegerField()
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
for m in (ClassRoom, Student, Mark):
editor.create_model(m)
a, b = ClassRoom.objects.create(name="10A"), ClassRoom.objects.create(name="10B")
for i, (name, room) in enumerate([("Asha", a), ("Ravi", a), ("Kiran", b), ("Meera", b)]):
s = Student.objects.create(name=name, class_room=room)
Mark.objects.create(student=s, subject="Maths", score=60 + i * 10)
Mark.objects.create(student=s, subject="Science", score=55 + i * 8)
from django.db.models import Prefetch
def count_queries(fn):
with CaptureQueriesContext(connection) as ctx:
fn()
return len(ctx.captured_queries)
naive = lambda: [s.class_room.name for s in Student.objects.all()]
joined = lambda: [s.class_room.name for s in Student.objects.select_related("class_room")]
print("FK naive:", count_queries(naive), "| select_related:", count_queries(joined))
naive_marks = lambda: [[m.score for m in s.marks.all()] for s in Student.objects.all()]
prefetched = lambda: [[m.score for m in s.marks.all()] for s in Student.objects.prefetch_related("marks")]
print("reverse FK naive:", count_queries(naive_marks), "| prefetch_related:", count_queries(prefetched))
qs = Student.objects.select_related("class_room").prefetch_related(
Prefetch("marks", queryset=Mark.objects.filter(score__gte=75).order_by("-score"), to_attr="good_marks")
)
with CaptureQueriesContext(connection) as ctx:
for s in qs:
print(s.name, s.class_room.name, [m.score for m in s.good_marks])
print("queries:", len(ctx.captured_queries))
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
FK naive: 5 | select_related: 1
reverse FK naive: 5 | prefetch_related: 2
Asha 10A []
Ravi 10A []
Kiran 10B [80]
Meera 10B [90, 79]
queries: 2
Key points
N+1 = one list query plus one query per row
select_related uses JOINs for single-valued relations
prefetch_related uses a second IN query for many-valued relations
Prefetch() filters or orders the related rows
Filtering a related manager in a loop defeats prefetching
Common mistakes
Using select_related on a reverse ForeignKey or ManyToMany (it raises FieldError)
Calling .filter() on a prefetched relation inside the loop
Adding select_related everywhere and producing huge JOINs that load unused columns
Only noticing N+1 in production because tests never count queries
Follow-ups
How would you prefetch only the latest mark per student?
What does to_attr change compared with a normal prefetch?
How do you detect N+1 queries in DRF serializers?
Tips
Show the query counts before and after, numbers make the answer concrete
Explain why prefetch does not use a JOIN
Mention assertNumQueries as a regression guard
19.django-0019Mediummid
What are F() expressions in Django, and how do they help avoid race conditions?
F("field") refers to a column's value inside the database instead of a Python value. obj.copies = F("copies") - 1 or Model.objects.filter(...).update(copies=F("copies") - 1) makes the database do the arithmetic in one UPDATE, so two simultaneous requests cannot overwrite each other's change. F() also compares two fields in one row, for example filter(score__gt=F("pass_mark")).
Full answer
The classic bug is a read-modify-write in Python:
python
book = Book.objects.get(pk=1)
book.copies = book.copies - 1
book.save()
If two librarians issue the last copies at the same moment, both requests read copies = 5, both compute 4 and both save 4. One loan is lost. This is a race condition: the result depends on timing.
This runs UPDATE book SET copies = copies - 1 WHERE id = 1. The database applies each update atomically, so two requests give 3, as expected.
On an instance, book.copies = F("copies") - 1; book.save() does the same. In Django 5.2, after saving, the attribute still holds the expression, not a number, so call book.refresh_from_db() before reading it, and saving the same instance again applies the expression a second time. Django 6.0 refreshes fields assigned expressions after save() on databases that support RETURNING (PostgreSQL, SQLite, Oracle), but refresh_from_db() remains the portable habit.
Order with null handling: .order_by(F("rank").asc(nulls_last=True))
Add a guard to avoid going negative: filter(pk=1, copies__gt=0).update(...) and check the returned row count. If 0 rows changed, there was no copy left. For multi-step logic where you must read and then decide, use select_for_update() inside a transaction.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.db import models, connection
from django.db.models import F
class Book(models.Model):
title = models.CharField(max_length=60)
copies = models.IntegerField()
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
editor.create_model(Book)
Book.objects.create(title="Train to Pakistan", copies=2)
# Two "requests" both read the old value first (the race)
r1 = Book.objects.get(pk=1)
r2 = Book.objects.get(pk=1)
r1.copies -= 1; r1.save()
r2.copies -= 1; r2.save()
print("read-modify-write result:", Book.objects.get(pk=1).copies, "(should be 0)")
# Reset and do it with F() instead
Book.objects.filter(pk=1).update(copies=2)
for _ in range(2):
Book.objects.filter(pk=1).update(copies=F("copies") - 1)
print("F() result:", Book.objects.get(pk=1).copies)
# Guarded issue: only succeeds while a copy is left
changed = Book.objects.filter(pk=1, copies__gt=0).update(copies=F("copies") - 1)
print("rows changed when none left:", changed)
b = Book.objects.get(pk=1)
b.copies = F("copies") + 5
b.save()
print(type(b.copies).__name__)
b.refresh_from_db()
print("after refresh:", b.copies)
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. The 'race' is simulated by reading twice before either save, which is what concurrent requests do.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
read-modify-write result: 1 (should be 0)
F() result: 0
rows changed when none left: 0
CombinedExpression
after refresh: 5
Key points
F() refers to a column value inside SQL
update(field=F(field) + n) is atomic per row
After save() with F(), refresh_from_db() before reading (automatic in Django 6.0 on RETURNING databases)
F() compares two columns in one filter
A conditional update plus row count is a simple stock guard
Common mistakes
Doing read-modify-write in Python for counters and stock
Reading an attribute right after saving an F() expression
Saving the same instance twice and applying the expression twice
Not checking update()'s row count when using a guard condition
Follow-ups
When is F() not enough and you need select_for_update()?
How would you implement a 'likes' counter that gets thousands of hits per minute?
Does update() call save() or send post_save signals?
Tips
Describe the lost update with two concrete requests
Show the SQL that F() produces
Mention that update() skips save() and signals
20.django-0020Mediummid
How do Q objects work in Django, and when do you need them?
Q objects wrap lookup conditions so you can combine them with | (OR), & (AND), ~ (NOT) and ^ (XOR, Django 4.2+). Keyword arguments to filter() are always ANDed, so OR conditions and negations of grouped conditions need Q. Q objects can also be built dynamically, for example from optional search fields.
Full answer
Keyword arguments in filter(a=1, b=2) mean a = 1 AND b = 2. That covers many cases, but not "students in 10A or with marks above 90".
Q turns each condition into an object you can combine:
python
from django.db.models import Q
Student.objects.filter(Q(class_room__name="10A") | Q(score__gte=90))
Operators:
| OR, & AND, ~ NOT, ^ XOR (Django 4.2+; emulated on databases without native XOR).
Brackets work as in maths: Q(a) & (Q(b) | Q(c)).
Mixing with keywords: Q objects must come before keyword arguments, filter(Q(...) | Q(...), is_active=True).
Building filters from optional inputs is a common real use:
python
cond = Q()
if name: cond &= Q(name__icontains=name)
if room: cond &= Q(class_room__name=room)
qs = Student.objects.filter(cond)
An empty Q() matches everything, which makes it a safe starting value.
exclude() vs ~Q: they are similar for simple fields. Across multi-valued relations the SQL differs, so check the generated query (print(qs.query)) when negating conditions on reverse ForeignKeys or ManyToMany.
Note a subtle point with multi-valued relations: filter(marks__subject="Maths", marks__score__gte=80) in one call requires the same mark row to match both. Chaining two filter() calls allows different rows. Q objects in one filter() behave like the single-call version.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.db import models, connection
from django.test.utils import CaptureQueriesContext
class ClassRoom(models.Model):
name = models.CharField(max_length=10)
class Meta:
app_label = "school"
class Student(models.Model):
name = models.CharField(max_length=40)
class_room = models.ForeignKey(ClassRoom, on_delete=models.CASCADE, related_name="students")
class Meta:
app_label = "school"
class Mark(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="marks")
subject = models.CharField(max_length=20)
score = models.IntegerField()
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
for m in (ClassRoom, Student, Mark):
editor.create_model(m)
a, b = ClassRoom.objects.create(name="10A"), ClassRoom.objects.create(name="10B")
for i, (name, room) in enumerate([("Asha", a), ("Ravi", a), ("Kiran", b), ("Meera", b)]):
s = Student.objects.create(name=name, class_room=room)
Mark.objects.create(student=s, subject="Maths", score=60 + i * 10)
Mark.objects.create(student=s, subject="Science", score=55 + i * 8)
from django.db.models import Q
top_or_10a = Student.objects.filter(Q(class_room__name="10A") | Q(marks__score__gte=90)).distinct()
print(sorted(top_or_10a.values_list("name", flat=True)))
not_10a = Student.objects.filter(~Q(class_room__name="10A"))
print(sorted(not_10a.values_list("name", flat=True)))
def search(name=None, room=None):
cond = Q()
if name:
cond &= Q(name__icontains=name)
if room:
cond &= Q(class_room__name=room)
return sorted(Student.objects.filter(cond).values_list("name", flat=True))
print(search(), search(name="ra"), search(name="r", room="10B"))
same_row = Student.objects.filter(marks__subject="Science", marks__score__gte=75)
any_rows = Student.objects.filter(marks__subject="Science").filter(marks__score__gte=75).distinct()
print(sorted(same_row.values_list("name", flat=True)), sorted(any_rows.values_list("name", flat=True)))
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py.
Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3):
['Asha', 'Meera', 'Ravi']
['Kiran', 'Meera']
['Asha', 'Kiran', 'Meera', 'Ravi'] ['Kiran', 'Meera', 'Ravi'] ['Kiran', 'Meera']
['Meera'] ['Kiran', 'Meera']
Key points
filter() keywords are ANDed; use Q for OR and NOT
| & ~ ^ combine Q objects
Q() is a safe empty starting point for dynamic filters
Positional Q arguments must come before keyword arguments
One filter() vs chained filter() differs on multi-valued relations
Common mistakes
Trying to OR conditions with two filter() calls (that ANDs them)
Putting keyword arguments before Q objects and getting a SyntaxError
Forgetting distinct() when an OR across a relation duplicates rows
Assuming chained filter() and single filter() behave the same on reverse relations
Follow-ups
What SQL does ~Q produce on a nullable field?
How would you build a search endpoint with five optional filters?
Why can OR across a relation return duplicate rows?
Tips
Show a dynamic Q() build, interviewers like the practical use
Know the four operators including XOR
Mention checking qs.query when negating across relations