skip to content

Django

2 roadmaps556 questionsupdated

Django's batteries-included stack: the ORM and migrations, routing and views, templates and forms, auth, admin, caching, async and testing. Interviewers use it to judge how you ship whole products.

on this pageshow

guide

overview

~2 min

Django is a batteries-included Python web framework. One install brings an ORM with migrations, URL routing, views, a template language, forms, authentication, an admin site, caching, security middleware and a test toolkit, all wired together by a settings module. Interviewers use it to judge whether you can ship and run a whole product rather than write one endpoint. The questions that separate candidates sit at the seams: what SQL a line of ORM code really sends, which middleware sees a request first, what happens to a write when the request fails halfway, and what stops working when `DEBUG` goes off. The hub follows the layers of a project. [Projects and settings](/topics/be-django-project) covers apps, configuration and the path a request takes. The data layer is [model classes](/topics/be-django-models-orm), [migration workflows](/topics/be-django-migrations), the [QuerySet API](/topics/be-django-queries), [ORM query tuning](/topics/be-django-orm-performance) and [databases and transactions](/topics/be-django-db). The request layer is the [URL dispatcher](/topics/be-django-views-routing), [views and responses](/topics/be-django-views), [class-based views](/topics/be-django-cbv), [middleware](/topics/be-django-middleware), [server-side templates](/topics/be-django-forms-templates) and [form processing](/topics/be-django-forms). Identity and safety come from [accounts and sign-in](/topics/be-django-auth-middleware), [access rights and groups](/topics/be-django-permissions), [sessions and messages](/topics/be-django-sessions), [built-in protections](/topics/be-django-security) and the [admin site](/topics/be-django-admin-drf). Around them sit [static and media files](/topics/be-django-static), the [cache toolkit](/topics/be-django-caching), [async support](/topics/be-django-async), [signals, tasks and email](/topics/be-django-background), [translation and locales](/topics/be-django-i18n), [logging and debugging](/topics/be-django-debugging), the [test toolkit](/topics/be-django-testing) and [running in production](/topics/be-django-deployment). Junior rounds check the contracts: what a view must return, how a route gets a name, what a migration file records, what a form does with submitted data. Middle and senior rounds turn to cost and failure — query counts on a list page, lost or duplicated side effects around transactions, stale caches, permission checks that only look enforced. Principal-level conversations are about running Django at scale: schema changes on a live database, the sync-and-async boundary, upgrades across releases. Start with how a project is put together and how a request travels through it, then models and QuerySets, because nearly every other section reads or writes through the ORM. Views, forms and templates come next; transactions, security and performance make sense once those are familiar.

primer

### A project is settings plus apps Almost nothing in Django is hard-wired. `INSTALLED_APPS` decides which apps exist, including the contrib ones that provide auth, sessions, admin and static files; `MIDDLEWARE`, `DATABASES`, `TEMPLATES` and `CACHES` decide how they are assembled. Many interview answers begin with "which setting controls this", and a surprising number of production incidents trace back to a setting that differs between environments. ### The request path is a fixed pipeline Every request enters through a WSGI or ASGI handler, passes down an ordered stack of middleware, gets matched to a view by the URLconf, and travels back up the same stack as a response. Ordering is part of the contract: a middleware can rely only on what the ones before it attached. When an answer needs to explain where the user, the session or a CSRF check comes from, it is describing a position in this stack. ### The model class is the schema; migrations are its history You describe tables as Python classes, and migration files record each change to them as code committed next to the models. The database keeps its own record of which files have run. Interviewers probe the gap between the two: branches that both add migrations, data migrations replayed years later on a fresh database, and column changes that lock a busy table. ### A QuerySet describes SQL; it does not run it Filters, annotations and slices compose a query lazily; rows arrive only when code needs them. That makes the ORM pleasant to write and easy to misuse, because the cost of a line is invisible. Senior rounds expect you to say how many queries a page sends and why — the N+1 pattern above all — and which tool moves work into the database or cuts the round trips. ### Transactions are opt-in Out of the box every statement is committed immediately. Grouping writes is an explicit choice, and so is deferring side effects such as emails or task enqueues until the data they describe has committed. Questions about lost writes, double charges and workers reading rows that do not exist yet all come back to where the transaction boundary sits. ### Validation lives in layers Forms and ModelForms clean incoming data; models can validate themselves but are not asked to on a plain save; the database enforces constraints last. Several write paths skip the middle layers entirely — bulk operations, queryset-level updates, raw SQL — along with any custom save logic and model signals. A strong answer names which layer owns each rule and which paths go around it. ### Safe defaults you can undo CSRF protection, template autoescaping, clickjacking headers and salted password hashing are on in a new project. HTTPS redirects, strict transport headers, secure cookies and a content security policy need settings. Interviewers want to hear which protections are on by default, which you must switch on, and what `DEBUG` exposes when left on. ### Sync core, async edges Django can serve `async def` views under ASGI, and the ORM offers a-prefixed async methods, but much of the framework, the database layer included, still runs synchronous code bridged onto threads. Async helps with slow external I/O; calling blocking code from an async context can stall the event loop or be refused outright. Knowing where the boundary sits is the senior part of every async question.

Project
The configured site: a settings module, a root URLconf and the WSGI and ASGI entry points, combining many apps into one deployable unit.
App
A Python package providing one set of features — models, views, templates, migrations — enabled by listing it in INSTALLED_APPS and described by an AppConfig.
URLconf
A module whose urlpatterns list maps URL paths to views, optionally including other URLconfs and naming routes so code can build URLs instead of hardcoding them.
View
Any callable that takes an HttpRequest and returns an HttpResponse, or raises an exception Django turns into one.
Class-based view
A view written as a class; as_view() turns it into a callable, and dispatch() routes each request to the method named after its HTTP verb.
Middleware
A component in the ordered MIDDLEWARE stack that wraps every request and response, able to act before the view, after it, or on its exceptions.
Model
A Python class describing one database table: its fields become columns, its relations become foreign keys, and its Meta holds table-level options.
Migration
A Python file recording a change to models as operations Django can apply to a database, with dependencies on earlier migrations.
QuerySet
A lazy, chainable description of a database query over one model; it runs SQL only when its rows are actually needed.
Manager
The interface through which a model gets its QuerySets, objects by default; custom managers add reusable query methods or change the default filtering.
N+1 query problem
Running one query for a list, then one more per row to load a related object; the most common ORM performance defect in reviews.
Atomic block
Code wrapped in transaction.atomic, whose queries commit together or roll back together; nested blocks become savepoints.
ModelForm
A form class generated from a model's fields, which validates submitted data against them and can save the result as a model instance.
CSRF token
A per-visitor secret that unsafe requests must echo back in a form field or header, proving they came from the site's own pages.
Session engine
The storage behind request.session — database, cache, files or a signed cookie — chosen with SESSION_ENGINE and keyed by the session cookie.
Signal
A hook that lets receivers run when something happens in the framework, such as a model save or a request starting, without the sender knowing them.
ASGI and WSGI
The Python server interfaces Django exposes: WSGI for synchronous request handling, ASGI for asynchronous handling and long-lived connections.

Follow one request. A WSGI or ASGI server hands it to Django's handler, which runs it down the middleware stack; security headers, the session, CSRF protection and the authenticated user each come from a middleware there, and their order matters. The URL resolver matches the path against the URLconf and calls the view with the request and captured arguments. The view talks to the models through QuerySets, often inside a transaction, validates input with a form, and renders a template with a context, or returns JSON, a redirect or a file. The response climbs back up through the same middleware, which can add headers, set cookies or cache it. A small view touches most of that path at once — a named route, a login guard, a query scoped to the current user with its relation joined in, and a template render: ```python # urls.py path("orders/<int:pk>/", views.order_detail, name="order-detail") # views.py @login_required def order_detail(request, pk): order = get_object_or_404( Order.objects.select_related("customer"), pk=pk, owner=request.user ) return render(request, "shop/order_detail.html", {"order": order}) ``` The owner filter is the authorization; the login guard only proves someone is signed in. That split, between who a user is and what they may touch, runs through the auth and permissions sections. The remaining sections attach to that path rather than beside it: - **The admin** is an app built from models, forms, class-based views and permissions; understanding those explains most of its behaviour. - **Caching** sits in middleware for whole pages, in templates for fragments, and in code for single values. - **Signals and tasks** hang work off model and request events; tasks and email should wait for the transaction to commit. - **Static files** bypass views in production, collected at deploy time and handed to a CDN, the front web tier or middleware; media files are user uploads and need their own storage and trust decisions. - **The test client** drives the same pipeline in process, so a test can exercise routing, middleware and templates together, against a throwaway database. - **Deployment** is the pipeline under a real server: the settings sweep, `collectstatic`, `migrate` and the process that replaces `runserver`.

  1. Projects & Settings →

    How apps, settings and manage.py fit together, and the path a request takes; every other section assumes this map.

  2. Model Classes →

    Models are the schema the rest of the framework reads and writes, so fields, relations and constraints come early.

  3. QuerySet API →

    How QuerySets compose and when they hit the database; the ORM questions in every other section build on it.

  4. Views & Responses →

    The request-in, response-out contract that routing, class-based views and middleware all wrap.

  5. Form Processing →

    Where submitted data gets validated and saved, and the bridge between views and models.

  6. Databases & Transactions →

    Transactions, commit hooks and locking: where writes get lost or duplicated once the basics are in place.

  • Treating a QuerySet as a list: truthiness tests, count() and slicing may each run a query, and a template loop over relations multiplies queries — see Related Object Loading.

  • Putting business rules only in an overridden save() or a post_save receiver, then updating rows with bulk or queryset-level calls that never run either.

  • Assuming save() validates the model: it does not call full_clean(), so only forms, explicit validation or database constraints catch bad data.

  • Sending email or enqueueing a task inside a transaction instead of after commit, so a rollback leaves the side effect behind or a worker reads rows that are not there yet.

  • Importing models from models.py inside a data migration; replayed later on a fresh database, the current class no longer matches that step's schema.

  • Adding a custom user model after the first migrate: AUTH_USER_MODEL is meant to be settled at project start, and switching later means manual schema and data work.

  • Fixing a 403 from a JavaScript POST with csrf_exempt instead of sending the token the middleware expects.

  • Checking login_required and calling it authorization; object-level ownership still has to be enforced in the query or a permission check.

  • Calling the synchronous ORM directly from an async view, which Django refuses with SynchronousOnlyOperation, or wrapping everything in adapters and losing the async benefit.

  • Leaving DEBUG on in production, or caching per-user pages under a key that ignores the user, so one visitor sees another's data.

This guide assumes the Django 6.x line, and notes where 5.2, the long-term-support release many production projects still run, behaves differently. Django ships a feature release roughly every eight months; each x.2 release is LTS with about three years of security support, which is why upgrade questions usually mean moving from one LTS to the next. Interviewers still ask about features by the release that brought them: - **3.0 and 3.1** added ASGI support and then `async def` views and async-capable middleware. - **4.0** added a built-in Redis cache backend and switched the default time-zone implementation to `zoneinfo`. - **4.1** added the async QuerySet interface — the a-prefixed methods — while the database layer stayed synchronous underneath. - **5.0** added database-computed defaults and generated fields, and made `USE_TZ` default to `True`. - **5.2** added composite primary keys. - **6.0** added a built-in content security policy, template partials and a background tasks API that defines tasks and backends but leaves production workers to other packages. - **6.1** added database-level cascades such as `DB_CASCADE`, which, being done by the database, send no delete signals. When an answer depends on these — async ORM calls, CSP, tasks, cascades — say which release you are describing.

Django rarely ships alone, and interviewers expect you to name the usual neighbours. For JSON APIs, Django REST Framework is the common layer on top, adding serializers, viewsets and API-oriented authentication and permissions; lighter type-hint-driven options such as Django Ninja also exist. Background work traditionally goes through Celery with a message broker, and the newer built-in tasks API still needs a separate worker implementation. Production runs under a WSGI server such as Gunicorn or an ASGI server such as Uvicorn or Daphne, typically with a reverse proxy in front; WhiteNoise serves static files from the application when no CDN does. django-allauth covers social login and MFA, pytest-django runs the test suite under pytest, and django-debug-toolbar shows queries and timings in development. Among frameworks, Django is weighed against Flask, a small core where you choose your own ORM, forms and auth, and FastAPI, an async-first API framework built around type hints without an admin or a bundled ORM. Rails and Laravel are the closest batteries-included peers in other languages. The trade-off to state is integration against freedom: Django's pieces are designed to work together and its admin comes for free, at the cost of doing things its way and a mostly synchronous core.

explore

report an issue with this guide →

questions

556 · 25 sections

In Django, what is the difference between a project and an app, and what do startproject and startapp each create?

level: juniorimportance: must knowfreq 70%
basics
~20 s

A Django project is the configured site: a settings module, a root URLconf and the WSGI/ASGI entry points. An app is a Python package providing one set of features, enabled by listing it in INSTALLED_APPS; one project combines many apps.

open as a page

In Django, why must the runserver development server never serve production traffic, and what serves the application instead?

level: juniorimportance: must knowfreq 68%
basics
~10 s

runserver is a convenience server built on Python's wsgiref that Django never security-audited or performance-tested. Production serves the same WSGI or ASGI application object from wsgi.py or asgi.py through a dedicated application server.

open as a page

In Django, what does DEBUG=True change, and what must you also set once DEBUG is False in production?

level: juniorimportance: must knowfreq 72%
basics
~20 s

DEBUG=True shows detailed tracebacks with settings and local variables, records every SQL query per connection, and trusts localhost when ALLOWED_HOSTS is empty. With DEBUG=False you must set ALLOWED_HOSTS, or every request returns 400 Bad Request.

open as a page

Django calls itself an MTV framework rather than MVC, so what do its model, template and view do, and where is the controller?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Django's model is the data layer, its view is the Python callable that decides which data a URL returns, and its template decides how that data looks. The framework itself, routing requests through the URLconf, plays MVC's controller.

open as a page

In Django, what is AppConfig.ready() for, and what should you avoid doing inside it?

level: middleimportance: must knowfreq 55%
basics
~20 s

AppConfig.ready() runs after every installed app's models are loaded, so it suits startup wiring such as importing signal receivers. Avoid database queries there: ready() runs on every management command and can run more than once in tests.

open as a page

In Django, what does include() do when a project's urls.py mounts an app's urls.py under a prefix such as 'comments/'?

level: juniorimportance: must knowfreq 60%
basics
~20 s

include() delegates to another URLconf: Django strips the part of the path matched by the prefix, here comments/, and resolves the remainder against the app's urlpatterns. Values captured in the prefix and any extra kwargs reach every included view.

open as a page

In Django's path() routes, what do the built-in str, int, slug, uuid and path converters match, and what does the view receive?

level: juniorimportance: must knowfreq 62%
basics
~20 s

str (the default) matches one non-empty segment without a slash; int matches digits and passes an int; slug matches ASCII letters, digits, hyphens and underscores; uuid matches a lowercase dashed UUID and passes uuid.UUID; path matches anything non-empty, slashes included.

open as a page

In a Django URLconf listing path('events/<slug:slug>/') before path('events/new/'), which view serves /events/new/, and why?

level: juniorimportance: must knowfreq 55%
basics
~20 s

The slug route serves it: Django tries urlpatterns in list order and calls the first pattern that matches, and 'new' is a valid slug. Listing the fixed events/new/ route above the converter route fixes it.

open as a page

In Django, what happens when a view raises Http404, and how does the response differ between DEBUG=True and DEBUG=False?

level: juniorimportance: must knowfreq 62%
basics
~20 s

Raising Http404 abandons the view and Django builds a 404. With DEBUG=True it shows a technical page listing the URL patterns tried; with DEBUG=False it calls handler404, which renders a 404.html template or a plain Not Found page.

open as a page

In Django, how do you build the URL of a route named 'job-detail' for job 42 in a view and in a template?

level: juniorimportance: must knowfreq 65%
basics
~10 s

In Python call django.urls.reverse('job-detail', kwargs={'pk': 42}) or args=[42]; in a template write {% url 'job-detail' pk=42 %}. Both find the route by its name= and return its path, such as /jobs/42/.

open as a page

In Django, what do require_POST, require_GET, require_safe and require_http_methods do, and what does a request with another method receive?

level: juniorimportance: must knowfreq 55%
basics
~10 s

They are view decorators from django.views.decorators.http that let only the listed HTTP methods reach the view. Any other method gets an HttpResponseNotAllowed: a 405 response with an Allow header naming the permitted methods.

open as a page

In Django, what must a function-based view accept and return, and what happens when it returns None?

level: juniorimportance: must knowfreq 58%
basics
~20 s

A Django function view takes the HttpRequest first, plus the URL's captured values as keyword arguments, and returns an HttpResponse or raises an exception Django maps to one. Returning None makes Django raise ValueError, surfacing as a 500.

open as a page

In Django, why is request.FILES empty after a user submits a form with a file input, and what must the request look like?

level: juniorimportance: must knowfreq 60%
basics
~10 s

Django fills request.FILES only for a POST request whose form used enctype="multipart/form-data" and actually sent a file. Without that enctype the browser sends only the file name as text, so FILES stays empty.

open as a page

In Django, why can't you put a function view decorator like require_POST directly on a class-based view method, and how does method_decorator fix it?

level: middleimportance: must knowfreq 52%
basics
~20 s

Function view decorators expect request as the first argument, but a method receives self first, so the decorator inspects the wrong object. method_decorator adapts the decorator to methods; apply it to dispatch() or to the class with name="dispatch".

open as a page

In Django, when does a plain function-based view beat a class-based view, and when does a generic class-based view earn its keep?

level: middleimportance: must knowfreq 72%
basics
~20 s

Function views win for bespoke flows, one-off endpoints and readability; generic class-based views win when a page matches a standard list, detail or form pattern or when many views share behaviour through mixins. Both satisfy the same request-in, response-out contract.

open as a page

In a Django URLconf, why do you route to MyView.as_view() instead of the class itself, and what does as_view() return?

level: juniorimportance: must knowfreq 62%
basics
~20 s

Django's path() needs a callable that takes a request and returns a response. MyView.as_view() returns such a function; on every request it builds a fresh MyView instance, calls setup(), then dispatch(), which runs the handler named after the HTTP method.

open as a page

In Django, what do ListView and DetailView need for a property index and property page, and which template and context names do they default to?

level: juniorimportance: must knowfreq 68%
basics
~10 s

Set model = Property. ListView renders listings/property_list.html with object_list and property_list; DetailView needs a pk or slug from the URL and renders listings/property_detail.html with object and property.

open as a page

In a Django function view, how do you paginate a QuerySet with Paginator, and what does the template loop over?

level: juniorimportance: must knowfreq 55%
basics
~10 s

Wrap the ordered QuerySet in Paginator(queryset, per_page), fetch the requested page with get_page(request.GET.get('page')), and pass that Page to the template, which loops over it and uses has_next() and next_page_number() for links.

open as a page

In Django, how do you serve a mostly static About page with TemplateView, and how do you add data to its template context?

level: juniorimportance: must knowfreq 55%
basics
~10 s

Route to TemplateView.as_view(template_name="about.html"); it renders that template on GET. Add fixed values with extra_context, or subclass and override get_context_data(), calling super() first so URL kwargs, view and extra_context stay in the context.

open as a page

In a Django ListView or DetailView, when do you set queryset versus override get_queryset(), and why is a class-level queryset safe to share?

level: middleimportance: must knowfreq 58%
basics
~20 s

Set queryset for a filter fixed at import time; override get_queryset() when it depends on the request, user or URL. The class-level QuerySet is safe because the generic get_queryset() hands each request a copy via .all().

open as a page

In Django templates, what does autoescaping do to a {{ review.body }} value, and which characters does it convert?

level: juniorimportance: must knowfreq 60%
basics
~20 s

Django's template engine HTML-escapes every variable's output by default, converting < > ' " and & to entities, after filters run and unless the value is already marked safe, so user text like a product review renders as text, not markup.

open as a page

In Django's TEMPLATES setting, what do DIRS and APP_DIRS do, and in what order does Django search for a template name?

level: juniorimportance: must knowfreq 58%
basics
~10 s

DIRS lists project template directories searched first, in order; APP_DIRS=True adds each installed app's templates/ subdirectory, searched in INSTALLED_APPS order. Django uses the first file that matches and raises TemplateDoesNotExist if none does.

open as a page

In Django templates, how do you apply, chain and pass an argument to a filter, as in {{ invoice.notes|truncatechars:80 }}?

level: juniorimportance: must knowfreq 58%
basics
~20 s

A filter follows a pipe inside {{ }} and transforms the value before output. Filters chain left to right, each receiving the previous result, and each takes at most one argument after a colon: a literal, a number or a variable.

open as a page

In Django templates, how do {% extends %}, {% block %} and {{ block.super }} work together to build a site-wide page layout?

level: juniorimportance: must knowfreq 72%
basics
~20 s

A child template starts with {% extends 'base.html' %}; each {% block %} it defines replaces the same-named block in the parent, blocks it skips keep the parent's default, and {{ block.super }} inserts the parent block's content instead of discarding it.

open as a page

In Django templates, how does {% for %} work together with {% empty %} and the forloop variable, such as forloop.counter and forloop.last?

level: juniorimportance: must knowfreq 62%
basics
~20 s

{% for item in items %} repeats its body per element; an {% empty %} clause renders instead when the sequence is empty or missing. Inside, forloop exposes counter, counter0, revcounter, revcounter0, first, last, length and parentloop.

open as a page

In Django forms, what is the difference between a bound and an unbound form, and when does cleaned_data exist?

level: juniorimportance: must knowfreq 72%
basics
~20 s

A Django form is bound when it is built with data= or files= (even an empty dict) and unbound otherwise. Only a bound form validates; cleaned_data appears once is_valid() or errors runs full_clean() on it.

open as a page

In Django, what does a ModelForm build from its model, and why must its Meta declare fields or exclude?

level: juniorimportance: must knowfreq 70%
basics
~20 s

A Django ModelForm generates a form field for each selected editable model field, mapping type, max_length, blank, choices, labels and help text, and its save() writes the instance. Meta must name fields or exclude, or class creation raises ImproperlyConfigured.

open as a page

In a Django template, what does {{ form }} output by default, and how do you render one field's label, errors and help text yourself?

level: juniorimportance: must knowfreq 55%
basics
~20 s

Since Django 5.0, {{ form }} renders django/forms/div.html: top-level errors, then one <div> per visible field holding its label, help text, errors and widget. By hand, use each BoundField's label_tag, help_text, errors and the field itself.

open as a page

In Django forms, how do Field and Widget responsibilities differ, and how would you give a sign-up form's date field a native date picker?

level: middleimportance: must knowfreq 56%
basics
~20 s

A Django Field coerces and validates input into a Python value; its Widget renders the HTML and extracts the raw value. For a native picker use DateInput(attrs={'type': 'date'}, format='%Y-%m-%d'), because browsers accept only ISO dates.

open as a page

With Django's inlineformset_factory, how do you save an order and its line items from one POST so every line references the order?

level: middleimportance: must knowfreq 52%
basics
~20 s

Bind a ModelForm for the order and an inline formset with instance=order to request.POST, validate both, save the order, set formset.instance to it and call formset.save(), which stamps each new line with the order's key.

open as a page

In a Django model, what is the difference between null=True and blank=True, and why avoid null=True on a CharField?

level: juniorimportance: must knowfreq 82%
basics
~20 s

null=True lets the database column store NULL; blank=True lets validation (forms and full_clean) accept an empty value. On CharField and TextField, Django's convention is blank=True with an empty string, so there is one 'no data' value, not two.

open as a page

In Django 6.x, what primary key does a model get when it declares none, and how do DEFAULT_AUTO_FIELD and AppConfig.default_auto_field change it?

level: juniorimportance: must knowfreq 55%
basics
~10 s

Django adds an auto-incrementing id field. Its class comes from the app's AppConfig.default_auto_field if set, otherwise from the DEFAULT_AUTO_FIELD setting, which defaults to BigAutoField since Django 6.0 (AutoField before).

open as a page

In a Django model, what is the inner class Meta for, and which options does it typically hold?

level: juniorimportance: must knowfreq 60%
basics
~20 s

class Meta holds model-level options rather than fields: the table name (db_table), default ordering, human-readable names, indexes, constraints and a few behaviour switches. Django reads it when building the model's _meta; it never becomes a column.

open as a page

In a Django model, what does a ForeignKey's on_delete argument decide, and how do you choose a value for each relation?

level: juniorimportance: must knowfreq 74%
basics
~20 s

on_delete tells Django what to do with rows that reference an object when that object is deleted: delete them too (CASCADE), refuse the delete (PROTECT, RESTRICT), or rewrite their key (SET_NULL, SET_DEFAULT, SET()). It is required on every ForeignKey and OneToOneField.

open as a page

How do Django's TextChoices and IntegerChoices work on a model field, and does choices= stop invalid values from reaching the database?

level: middleimportance: must knowfreq 58%
basics
~20 s

TextChoices and IntegerChoices are enums whose members carry a stored value and a human label; pass the class as choices=. Choices are enforced by model validation and forms only, so save(), update() or raw SQL can still store any value.

open as a page

In Django's ORM, what is the difference between aggregate() and annotate(), and what does each one return?

level: juniorimportance: must knowfreq 70%
basics
~10 s

aggregate() computes summary values over the whole QuerySet and immediately returns a dict. annotate() adds a computed value to every object and returns a new, lazy QuerySet you can keep filtering and ordering.

open as a page

In Django's ORM, what does it mean that a QuerySet is lazy, and which operations make it actually query the database?

level: juniorimportance: must knowfreq 78%
basics
~20 s

Building or chaining a QuerySet only composes a query and returns a new QuerySet. SQL runs when Python needs rows: iteration, list(), len(), bool() or an if test, repr(), a slice with a step, or pickling.

open as a page

In Django's ORM, what is the difference between filter() and get(), and which exceptions can get() raise?

level: juniorimportance: must knowfreq 75%
basics
~10 s

filter() returns a lazy QuerySet of zero or more rows and never raises for no matches. get() runs immediately and returns exactly one instance, raising Model.DoesNotExist for none and Model.MultipleObjectsReturned for more than one.

open as a page

In Django, when do you use Manager.raw() rather than connection.cursor(), and what does each one give you back?

level: juniorimportance: must knowfreq 55%
basics
~20 s

Manager.raw() runs a SELECT and returns a lazy RawQuerySet of model instances, matched to fields by column name, so the primary key must be selected. connection.cursor() bypasses models: it runs any statement and returns plain tuples.

open as a page

A Django dashboard view runs the same SELECT four times; how does the QuerySet result cache explain it, and what fixes it?

level: middleimportance: must knowfreq 60%
basics
~20 s

Each QuerySet caches its own rows after its first full evaluation, but helpers, .all(), filter() and template lookups like user.orders.all build new QuerySets with empty caches. Evaluate one QuerySet once and reuse that object everywhere.

open as a page

In Django's ORM, why is filter(...).update(loyalty_points=F('loyalty_points') + 50) better than a loop that loads each customer, adds 50 and calls save()?

level: juniorimportance: must knowfreq 63%
basics
~20 s

update() with F() sends one UPDATE that adds 50 to the stored value inside the database: one round trip, no lost updates. The save() loop runs a SELECT plus an UPDATE per customer and can overwrite concurrent changes.

open as a page

In Django, what do values() and values_list() return instead of model instances, and what do flat=True and named=True change?

level: juniorimportance: must knowfreq 60%
basics
~10 s

values() yields dictionaries keyed by field name and values_list() yields tuples, both skipping model instances. flat=True with one field returns bare values; named=True returns namedtuples called Row.

open as a page

In Django, how do you see the SQL your ORM code runs with connection.queries and str(queryset.query), and how do the two differ?

level: juniorimportance: must knowfreq 58%
basics
~10 s

str(queryset.query) previews the SELECT one QuerySet would run, with parameters crudely pasted in; django.db.connection.queries logs every statement actually executed on that connection, with timings, but only while DEBUG is True.

open as a page

In Django's ORM, what do QuerySet.only() and defer() do, and what does reading a deferred field cost you later?

level: middleimportance: must knowfreq 55%
basics
~20 s

defer() leaves named columns out of the SELECT and only() loads just the named ones; you still get model instances. Reading a skipped field later runs one extra query for that instance under the default FETCH_ONE mode.

open as a page

In Django, what does the default autocommit mode mean for a two-wallet transfer, and how does transaction.atomic change it?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Django runs in autocommit, so every ORM query commits on its own. transaction.atomic, used as a decorator or a with-block, runs its queries in one transaction: committed if the block exits normally, rolled back if an exception escapes it.

open as a page

In Django, what does the DATABASES setting define, and what do you change to move a prototype from SQLite to PostgreSQL?

level: juniorimportance: must knowfreq 60%
basics
~20 s

DATABASES maps aliases such as default to connection settings: ENGINE picks the backend, NAME the database, plus USER, PASSWORD, HOST, PORT and OPTIONS. Moving to PostgreSQL means installing psycopg, setting ENGINE to django.db.backends.postgresql with credentials, and running migrate.

open as a page

In Django, what does transaction.on_commit() do, and why send an order's receipt email through it rather than straight after save()?

level: juniorimportance: must knowfreq 55%
basics
~20 s

transaction.on_commit() registers a callable to run after the current transaction commits and drops it if the transaction rolls back. Sending the receipt from it means no customer is emailed about an order that was never saved.

open as a page

In Django, how does select_for_update() stop two flash-sale buyers from both taking the last unit, and why must it run inside transaction.atomic()?

level: juniorimportance: must knowfreq 58%
basics
~20 s

select_for_update() makes the query lock the rows it returns until the transaction ends, so a second buyer's read waits until the first commits. Outside atomic, autocommit would release the lock at once, so Django raises TransactionManagementError.

open as a page

Why can a Django project whose tests all pass on SQLite still break when it runs on PostgreSQL or MySQL in production?

level: middleimportance: must knowfreq 55%
basics
~20 s

The ORM hides SQL syntax, not engine behaviour: SQLite matches strings differently, stores decimals as floats, ignores select_for_update(), rebuilds tables for schema changes and serialises writers, so code tested only on SQLite can fail or change results on PostgreSQL or MySQL.

open as a page

In Django, what is the difference between makemigrations and migrate, and how does Django know which migrations a database has already applied?

level: juniorimportance: must knowfreq 82%
basics
~10 s

makemigrations writes migration files describing model changes; migrate runs unapplied migration files against a database. Each applied migration is recorded as an (app, name, applied) row in that database's django_migrations table.

open as a page

After merging two branches that each added an orders migration 0042, why does Django's migrate report multiple leaf nodes, and how do you fix it?

level: juniorimportance: must knowfreq 48%
basics
~20 s

Both 0042 files depend on 0041, so the orders app's migration graph ends in two leaf nodes and Django refuses to guess their order. Run makemigrations --merge to add a migration depending on both, after checking they touch different fields.

open as a page

In Django, what do the dumpdata and loaddata management commands do, and where does loaddata look for fixture files?

level: juniorimportance: must knowfreq 55%
basics
~20 s

dumpdata writes database rows out as a fixture (JSON by default; XML, JSONL or YAML on request) and loaddata reads fixtures back in one transaction, searching each installed app's fixtures directory, then FIXTURE_DIRS, then the current directory.

open as a page

In Django, how do you write a data migration that fills new first_name and last_name columns from an existing full_name column?

level: juniorimportance: must knowfreq 55%
basics
~20 s

Create an empty migration with makemigrations --empty, write a function taking (apps, schema_editor) that loads the model via apps.get_model and fills the new columns, and add it to operations as migrations.RunPython, ideally with a reverse function.

open as a page

In a Django data migration, why must RunPython code load models with apps.get_model() instead of importing them from models.py?

level: middleimportance: must knowfreq 58%
basics
~20 s

apps.get_model() returns the historical model rebuilt from the migrations up to that point; an imported model is today's class, so replaying old migrations on a fresh database breaks once its fields no longer match that step's schema.

open as a page

How do you register a model with Django's admin, and how do you choose the columns its change list shows?

level: juniorimportance: must knowfreq 62%
basics
~10 s

Register a model in the app's admin.py with admin.site.register(Ticket, TicketAdmin) or the @admin.register(Ticket) decorator on a ModelAdmin subclass. The change list shows the columns named in ModelAdmin.list_display, defaulting to the object's str.

open as a page

In Django, what do the is_staff and is_superuser user flags each control, and can a superuser without is_staff use the admin?

level: juniorimportance: must knowfreq 62%
basics
~20 s

is_staff lets an active user into the Django admin; is_superuser makes has_perm() return True for every permission. They are independent: a superuser with is_staff=False cannot log in to the admin, and a staff user with no permissions sees nothing to edit.

open as a page

How do you restrict a Django admin action so only staff holding a custom 'ship order' permission can see and run it?

level: middleimportance: must knowfreq 50%
basics
~10 s

Pass permissions=["ship"] to @admin.action and define has_ship_permission(self, request) on the ModelAdmin. The admin hides the action from users failing every listed check and refuses a forged POST for it; per-object checks remain your job.

open as a page

How do you add a custom Django admin action that marks the selected orders as shipped, and what does the action function receive?

level: middleimportance: must knowfreq 60%
basics
~10 s

Write a function taking (modeladmin, request, queryset), decorate it with @admin.action(description=...), and list it in the ModelAdmin's actions. The queryset holds the ticked rows; returning None sends the user back to the change list.

open as a page

In Django's admin, how do you edit a course's lessons on the course's own change form, and when do you choose TabularInline over StackedInline?

level: middleimportance: must knowfreq 55%
basics
~20 s

Define a TabularInline or StackedInline subclass with model = Lesson and list it in the course ModelAdmin's inlines. Tabular renders one compact row per lesson, stacked renders each lesson as a full form; the only difference is the template.

open as a page

In Django's contrib.auth, what is the difference between authenticate() and login(), and why does a sign-in view call both?

level: juniorimportance: must knowfreq 76%
basics
~20 s

authenticate() checks credentials against the configured backends and returns a user or None without changing any state. login() takes that user and records it in the session, so later requests arrive with request.user set. A sign-in view needs both steps.

open as a page

In Django, how do you restrict a view to signed-in users with login_required or LoginRequiredMixin, and what happens to an anonymous visitor?

level: juniorimportance: must knowfreq 72%
basics
~10 s

Decorate a function view with @login_required or put LoginRequiredMixin first in a class-based view's bases. An anonymous request is redirected to settings.LOGIN_URL (default /accounts/login/) with ?next= carrying the original path.

open as a page

In Django, when would you build a custom user model on AbstractUser rather than on AbstractBaseUser with PermissionsMixin?

level: middleimportance: must knowfreq 74%
basics
~20 s

Subclass AbstractUser to keep the full default user and add fields. Use AbstractBaseUser when the identity shape differs: it supplies only password and last_login, so you define the fields, USERNAME_FIELD and a manager, adding PermissionsMixin for groups.

open as a page

In Django, how does authenticate() walk the AUTHENTICATION_BACKENDS list, and how does a backend returning None differ from raising PermissionDenied?

level: middleimportance: must knowfreq 52%
basics
~10 s

authenticate() tries each backend in AUTHENTICATION_BACKENDS order and returns the first user found. Returning None passes to the next backend; raising PermissionDenied stops the chain, so authenticate() returns None without trying later backends.

open as a page

How would you write a custom Django authentication backend that lets users sign in with their email address and password?

level: middleimportance: must knowfreq 62%
basics
~10 s

Subclass ModelBackend, override authenticate() to look the user up by email case-insensitively, check_password() it, return the user only if user_can_authenticate() passes, and add the class to AUTHENTICATION_BACKENDS. get_user() and permissions are inherited.

open as a page

In Django, how do you restrict a function-based view to users holding a given permission, and what happens when they lack it?

level: juniorimportance: must knowfreq 62%
basics
~10 s

Decorate the view with permission_required("app_label.codename") from django.contrib.auth.decorators. Any user lacking it, logged in or not, is redirected to LOGIN_URL with a next parameter; raise_exception=True raises PermissionDenied and yields a 403 instead.

open as a page

In Django's contrib.auth, which permissions does every model get automatically, and how do you check one with has_perm()?

level: juniorimportance: must knowfreq 62%
basics
~10 s

Django creates add, change, delete and view permissions for every model when migrate runs. You check one with user.has_perm('app_label.codename'), for example has_perm('newsroom.change_article'), where the codename is the action plus the lowercase model name.

open as a page

In Django, how does a user get permissions through a Group, and how do group grants combine with user.user_permissions?

level: juniorimportance: must knowfreq 58%
basics
~20 s

A Group holds a set of permissions, and every user in user.groups inherits them. ModelBackend takes the union of the group permissions and the direct user.user_permissions, so a permission from either source grants access and nothing can subtract one.

open as a page

In Django, how does PermissionRequiredMixin enforce a permission on a class-based view, and how do you customise what a denied user gets?

level: middleimportance: must knowfreq 58%
basics
~10 s

PermissionRequiredMixin checks request.user.has_perms() in dispatch(), before get() or post(). On failure handle_no_permission() raises PermissionDenied (403) for logged-in users and redirects anonymous ones to login unless raise_exception is True; override has_permission() or handle_no_permission() to customise.

open as a page

In a Django property-listings app, how do you make sure owners can edit only their own listings?

level: middleimportance: must knowfreq 60%
basics
~20 s

Fetch the listing through a queryset limited to the user, such as get_object_or_404(Listing, pk=pk, owner=request.user), so another owner's listing returns 404. Apply the same scoping to list, update and delete views, and never rely on change_listing alone.

open as a page

What order does Django's startproject MIDDLEWARE list use, and why must SessionMiddleware come before AuthenticationMiddleware?

level: juniorimportance: must knowfreq 66%
basics
~10 s

Security, Session, Common, Csrf, Authentication, Messages, XFrameOptions. AuthenticationMiddleware reads the logged-in user's id from request.session, which SessionMiddleware attaches; listed first, it raises ImproperlyConfigured. The default message storage needs the session too.

open as a page

How do you write a custom Django middleware, and which part of it runs once versus on every request?

level: juniorimportance: must knowfreq 62%
basics
~10 s

Write a factory that receives get_response: a class whose init(self, get_response) runs once at startup and whose call(self, request) runs per request, calling get_response and returning the response. Register its dotted path in MIDDLEWARE.

open as a page

How do you write a Django middleware, such as a tenant resolver, that runs in both WSGI and ASGI deployments without an adapter?

level: middleimportance: must knowfreq 45%
basics
~10 s

Declare a Django middleware hybrid with sync_and_async_middleware (or both class flags True), check inspect.iscoroutinefunction(get_response) once in the factory, and return an async def callable for async stacks and a plain function for sync ones.

open as a page

In Django, what do a middleware's sync_capable and async_capable attributes declare, and what are their defaults?

level: juniorimportance: should knowfreq 38%
basics
~20 s

They declare which request modes a Django middleware factory can handle: sync_capable defaults to True and async_capable to False, so an undecorated middleware is sync-only and Django adapts it with a thread hop under ASGI.

open as a page

In Django's MIDDLEWARE, where do GZipMiddleware, LocaleMiddleware and CommonMiddleware belong relative to the other built-ins, and why?

level: middleimportance: should knowfreq 40%
basics
~20 s

GZipMiddleware goes above anything that reads or changes the response body, so it compresses the final bytes. LocaleMiddleware goes after SessionMiddleware and before CommonMiddleware. CommonMiddleware stays near the top; middleware above it that changes the body must reset Content-Length.

open as a page

In a Django view, why does appending to a list stored in request.session not persist to the next request?

level: juniorimportance: must knowfreq 52%
basics
~20 s

Django saves request.session only when it is marked modified, and only assignments or deletions on the session itself set that flag. Mutating a nested list does not, so reassign the key or set request.session.modified = True.

open as a page

In Django, how do you show a one-time 'Profile saved' notice on the page a user is redirected to?

level: juniorimportance: must knowfreq 55%
basics
~10 s

Call messages.success(request, 'Profile saved.') from django.contrib.messages before returning the redirect, and loop over messages in the base template; MessageMiddleware stores the notice across the redirect and iteration clears it.

open as a page

In Django's django.core.signing, what does Signer.sign() guarantee about a value, and why can anyone still read the signed result?

level: juniorimportance: must knowfreq 45%
basics
~10 s

Signer.sign() appends an HMAC-SHA256 signature derived from SECRET_KEY, so unsign() detects any change and raises BadSignature. It does not encrypt: the value, or its base64 JSON, travels in the clear.

open as a page

In Django, which session engines can SESSION_ENGINE select, which is the default, and how do they differ?

level: middleimportance: must knowfreq 55%
basics
~10 s

Django's SESSION_ENGINE selects db (the default, a django_session table), cache, cached_db (database with a write-through cache), file, or signed_cookies (data in a signed cookie); they differ in durability, speed, fleet-sharing and revocability.

open as a page

In Django 6.x, how do you enable the built-in Content Security Policy, and what do SECURE_CSP and SECURE_CSP_REPORT_ONLY control?

level: juniorimportance: must knowfreq 40%
basics
~10 s

Add django.middleware.csp.ContentSecurityPolicyMiddleware to MIDDLEWARE and fill SECURE_CSP (enforced header) and/or SECURE_CSP_REPORT_ONLY (report-only header) with directive dictionaries. Both default to {}, which sends no header.

open as a page

In a Django template, what does {% csrf_token %} add to a POST form, and why does the submit fail with 403 without it?

level: juniorimportance: must knowfreq 80%
basics
~20 s

{% csrf_token %} renders a hidden csrfmiddlewaretoken input carrying a masked copy of the visitor's CSRF secret. CsrfViewMiddleware answers 403 Forbidden to a POST whose token is missing or does not match the csrftoken cookie.

open as a page

In Django, what does the ALLOWED_HOSTS setting do, and why does a site start answering 400 Bad Request right after DEBUG is set to False?

level: juniorimportance: must knowfreq 66%
basics
~20 s

ALLOWED_HOSTS lists the domain names a Django site may serve; request.get_host() rejects any other Host with DisallowedHost, a 400. An empty list is only tolerated for localhost while DEBUG=True, so switching DEBUG off without filling it breaks every request.

open as a page

A Django page's fetch() POST returns 403 'CSRF token missing'; how do you send the token correctly instead of exempting the view?

level: middleimportance: must knowfreq 72%
basics
~20 s

Read the token from the csrftoken cookie, or from a rendered csrfmiddlewaretoken input, and send it in an X-CSRFToken request header. Django reads the token only from form-encoded POST data or that header, never from a JSON body.

open as a page

A Django site behind a TLS-terminating load balancer enables SECURE_SSL_REDIRECT and every page now loops with redirects; why, and how do you fix it?

level: middleimportance: must knowfreq 60%
basics
~10 s

The balancer talks plain HTTP to Django, so request.is_secure() is False and SecurityMiddleware redirects HTTPS users again forever. Set SECURE_PROXY_SSL_HEADER to the header the balancer sets, or redirect at the balancer instead.

open as a page

In Django, what are STATIC_URL, STATIC_ROOT and STATICFILES_DIRS each for, and why should templates use the {% static %} tag?

level: juniorimportance: must knowfreq 72%
basics
~20 s

STATIC_URL is the URL prefix static files are served under; STATIC_ROOT is the one directory collectstatic copies into; STATICFILES_DIRS lists extra project-wide source directories. {% static %} gets each URL from the staticfiles storage instead of hard-coding it.

open as a page

In Django, what is the difference between MEDIA_ROOT and MEDIA_URL, and what does a FileField actually store in the database?

level: juniorimportance: must knowfreq 60%
basics
~20 s

MEDIA_ROOT is the filesystem directory where Django's default FileSystemStorage writes uploads; MEDIA_URL is the public URL prefix for them. A FileField stores only the file's name relative to the storage root, and .url asks the storage to build the link.

open as a page

How do you serve a Django app's static files with WhiteNoise when it runs in a single container with no separate web server?

level: juniorimportance: must knowfreq 55%
basics
~10 s

Install WhiteNoise, add WhiteNoiseMiddleware right after SecurityMiddleware, set STATIC_ROOT and STORAGES['staticfiles'] to CompressedManifestStaticFilesStorage, and run collectstatic while building the image so the files exist before the app starts.

open as a page

Why does a Django site's CSS load under runserver with DEBUG = True but return 404 as soon as DEBUG is set to False?

level: middleimportance: must knowfreq 66%
basics
~20 s

With DEBUG on, staticfiles' runserver serves files straight from the finders. With DEBUG off that handler is not installed and nothing serves STATIC_URL, so run collectstatic and serve STATIC_ROOT from a web server, CDN or static-serving middleware.

open as a page

In Django, how does ManifestStaticFilesStorage bust browser caches for static files, and what is stored in staticfiles.json?

level: middleimportance: must knowfreq 55%
basics
~20 s

ManifestStaticFilesStorage saves, during collectstatic, a copy of each static file named with a 12-character MD5 content hash and records original-to-hashed names in staticfiles.json; {% static %} resolves through that map, so a changed file gets a new URL.

open as a page

With Django's low-level cache API, how do cache.set(), cache.get() and cache.add() behave, and what do timeout=None and timeout=0 mean?

level: juniorimportance: must knowfreq 62%
basics
~20 s

Django's cache.set(key, value, timeout) stores a picklable value, cache.get(key, default) returns it or the default on a miss, and cache.add() stores only if the key is absent. timeout=None means never expire; timeout=0 means do not cache.

open as a page

What does Django's cache_page decorator do, and what do its timeout, cache and key_prefix arguments control?

level: juniorimportance: must knowfreq 60%
basics
~20 s

Django's cache_page stores a view's whole GET or HEAD response in the cache and serves it for later requests to the same URL. timeout is the lifetime in seconds, cache picks the CACHES alias, and key_prefix namespaces the keys.

open as a page

A Django weather-forecast site runs on three servers; which built-in cache backend would you pick for its CACHES default, and why?

level: middleimportance: must knowfreq 55%
basics
~20 s

Pick a shared network backend, RedisCache or PyMemcacheCache, so all three servers and every worker read the same forecasts. DatabaseCache works when no cache server is allowed; LocMemCache, FileBasedCache and DummyCache do not share across servers.

open as a page

Why does Django's LocMemCache backend give inconsistent results once a site runs under several worker processes?

level: middleimportance: must knowfreq 62%
basics
~20 s

LocMemCache keeps entries in a Python dict inside each process. With several worker processes every worker has its own private copy, so a set or delete in one worker is invisible to the others and readers see stale or missing values.

open as a page

How does Django's {% cache %} template tag cache a fragment per user or language, and how do you invalidate that fragment from Python code?

level: middleimportance: must knowfreq 48%
basics
~20 s

Django's {% cache timeout name var1 var2 %} stores the rendered block under a key from the fragment name and the extra arguments' string values. To invalidate, rebuild it with make_template_fragment_key(name, [vars]) and delete it from the same alias.

open as a page

In Django's async ORM, which QuerySet calls need an a-prefixed version in an async view, and which can you chain as usual?

level: juniorimportance: must knowfreq 52%
basics
~10 s

QuerySet builders such as filter(), exclude() and order_by() run no SQL, so they stay unchanged. Calls that execute a query use awaited a-prefixed versions: aget(), afirst(), acount(), acreate(). Iterate with async for.

open as a page

In Django, how do you write an async view, both as a function-based view and as a class-based view?

level: juniorimportance: must knowfreq 58%
basics
~20 s

Declare a function-based view with async def. For a class-based view, declare its HTTP handlers such as get() and post() with async def, leaving as_view() alone; the handlers must be all async or all sync.

open as a page

In Django, what do asgiref's sync_to_async() and async_to_sync() do, and when do you reach for each?

level: middleimportance: must knowfreq 55%
basics
~20 s

sync_to_async wraps a sync function so async code can await it, running it on a worker thread. async_to_sync wraps a coroutine function so sync code can call it and block for the result. Django uses both internally.

open as a page

A Django async view calls three shipping-rate APIs concurrently; what does it gain under WSGI, and what more under ASGI?

level: middleimportance: must knowfreq 52%
basics
~20 s

Under both, asyncio.gather overlaps the three calls, so that request takes roughly as long as the slowest one. Only under ASGI does the process serve other requests while it awaits; under WSGI it holds a worker for the whole request.

open as a page

In Django, why does an async view that calls Invoice.objects.get() raise SynchronousOnlyOperation, and how do you fix it?

level: juniorimportance: should knowfreq 48%
basics
~20 s

Django guards its database layer as async-unsafe: when a guarded call runs in a thread with a running event loop, it raises SynchronousOnlyOperation. Use the async ORM API or wrap the sync code in sync_to_async; never DJANGO_ALLOW_ASYNC_UNSAFE.

open as a page

How do you wire Celery into a Django project, and what goes into celery.py and the project package's __init__.py?

level: juniorimportance: must knowfreq 58%
basics
~10 s

Create proj/celery.py that sets DJANGO_SETTINGS_MODULE, builds Celery('proj'), calls config_from_object('django.conf:settings', namespace='CELERY') and autodiscover_tasks(); then import that app in proj/init.py so it loads whenever Django starts.

open as a page

In Django, when is send_mail() enough, and when do you build an EmailMessage or EmailMultiAlternatives instead?

level: juniorimportance: must knowfreq 62%
basics
~20 s

send_mail() sends one message, optionally with an html_message alternative, to a recipient list that all appear in To. For CC, BCC, Reply-To, custom headers or attachments, build an EmailMessage, or an EmailMultiAlternatives to add body versions.

open as a page

In Django, how would you create a Profile row automatically whenever a new user signs up, using a post_save receiver?

level: juniorimportance: must knowfreq 72%
basics
~10 s

Connect a receiver to post_save with sender=settings.AUTH_USER_MODEL and create the Profile only when the created argument is True, so later saves of the same user do not insert a second profile.

open as a page

A Django post_save receiver keeps a search index in sync, yet some edits never reach it; which ORM calls bypass model signals?

level: middleimportance: must knowfreq 64%
basics
~10 s

QuerySet.update(), bulk_create() and bulk_update() write SQL directly and send no pre_save or post_save; raw SQL sends nothing; DB_CASCADE deletes (Django 6.1) send no delete signals. QuerySet.delete() still sends pre_delete and post_delete per object.

open as a page

A Django view creates an order in a transaction and queues a Celery email task that intermittently raises Order.DoesNotExist; what is wrong?

level: seniorimportance: must knowfreq 60%
basics
~20 s

The task is queued before the transaction commits, so the worker's separate connection may not see the order yet. Queue it with transaction.on_commit(), or Celery's delay_on_commit() on Django projects, so the message is sent only after commit.

open as a page

In Django, how do you mark a user-facing string for translation in Python code and in a template?

level: juniorimportance: must knowfreq 58%
basics
~20 s

In Python, wrap the string in gettext(), usually imported as _. In a template, add {% load i18n %}, then use {% translate %} for a constant string or {% blocktranslate %} for a sentence with variables. Use named placeholders, never f-strings.

open as a page

In a Django project with USE_TZ enabled, why use django.utils.timezone.now() instead of datetime.datetime.now()?

level: juniorimportance: must knowfreq 60%
basics
~20 s

With USE_TZ on, timezone.now() returns an aware datetime in UTC, matching how Django stores datetimes. datetime.now() is naive local time: saving it makes Django warn and assume TIME_ZONE, and comparing it with aware values raises TypeError.

open as a page

In Django, what do makemessages and compilemessages each do, and why does a project need both .po and .mo files?

level: middleimportance: must knowfreq 52%
basics
~20 s

makemessages scans source files for marked strings and creates or updates a human-editable .po file per language. compilemessages turns each .po into the binary .mo file that Django actually loads at runtime. Translators edit .po; Django reads only .mo.

open as a page

In Django, in what order does LocaleMiddleware look for a request's language, and what happens when nothing matches?

level: middleimportance: must knowfreq 55%
basics
~10 s

LocaleMiddleware tries the URL language prefix (only under i18n_patterns), then the django_language cookie, then the Accept-Language header by q-value, and finally LANGUAGE_CODE. Each candidate must match a language in LANGUAGES.

open as a page

In Django, why must a model field's verbose_name or a form field's label use gettext_lazy() instead of gettext()?

level: middleimportance: must knowfreq 66%
basics
~20 s

Model and form fields are class attributes, evaluated once when the module is imported, before any request activates a language. gettext() would translate at that moment. gettext_lazy() returns a proxy that translates whenever it is rendered, in the language active for that request.

open as a page

In Django, what does a visitor see when a view raises an unhandled exception with DEBUG = True, and what changes with DEBUG = False?

level: juniorimportance: must knowfreq 72%
basics
~20 s

With DEBUG = True Django returns its technical 500 page: traceback, local variables, request data and most settings. With DEBUG = False the visitor gets the 500.html template, and the details go to logging and ADMINS emails.

open as a page

How does Django apply your LOGGING setting on top of DEFAULT_LOGGING, and why is disable_existing_loggers usually set to False?

level: middleimportance: must knowfreq 52%
basics
~10 s

Django runs dictConfig(DEFAULT_LOGGING), then your LOGGING as a second pass. With disable_existing_loggers True, the dictConfig default, loggers you don't name, including django.request, are disabled and silently drop 500-error records and admin emails.

open as a page

A Django checkout page takes three seconds locally; how do you use django-debug-toolbar's panels to find where the time goes?

level: middleimportance: must knowfreq 56%
basics
~20 s

Read the Timer panel to see whether time is CPU or waiting, then the SQL panel's count, slow queries and similar or duplicated groups, whose stack traces point at the triggering line. Templates, Cache and Signals panels explain the rest.

open as a page

In a new Django project with no LOGGING setting, where do Django's log records go when DEBUG is True, and when it is False?

level: juniorimportance: should knowfreq 40%
basics
~20 s

DEFAULT_LOGGING sends the django logger's INFO and above to the console when DEBUG is True. When DEBUG is False, only ERROR and above leave, emailed to ADMINS by AdminEmailHandler; everything else is dropped. runserver's django.server lines always print.

open as a page

In a Django project, how do you install django-debug-toolbar, and why might it still not appear on your pages?

level: juniorimportance: should knowfreq 50%
basics
~20 s

Add debug_toolbar to INSTALLED_APPS, its URLs via debug_toolbar_urls(), DebugToolbarMiddleware early in MIDDLEWARE, and 127.0.0.1 to INTERNAL_IPS. It stays hidden if DEBUG is False, your IP is not internal, or the response is not HTML with a </body>.

open as a page

In Django's test framework, how do SimpleTestCase, TransactionTestCase and TestCase differ, and which one should most tests use?

level: juniorimportance: must knowfreq 66%
basics
~20 s

SimpleTestCase forbids database queries. TransactionTestCase lets code commit and then truncates every table after each test. TestCase wraps each test in a transaction rolled back at the end, which is much faster, so most database tests use TestCase.

open as a page

In Django testing, what is the difference between the test Client and RequestFactory, and when would you reach for each?

level: juniorimportance: must knowfreq 62%
basics
~20 s

Django's test Client runs a request through URL routing, every middleware and template rendering, like an in-process browser. RequestFactory only builds a request object you pass to one view yourself, with no middleware, so you set request.user and session by hand.

open as a page

When you run Django's manage.py test, which database do the tests use, and what happens to it before and after the run?

level: juniorimportance: must knowfreq 58%
basics
~20 s

Django's test runner creates a separate database named 'test_' plus each NAME in DATABASES (in memory for SQLite), runs migrate into it, runs the tests, and destroys it at the end unless --keepdb is passed.

open as a page

In a Django TestCase, how do you assert that a sign-up view sends exactly one welcome email from an overridden DEFAULT_FROM_EMAIL?

level: juniorimportance: must knowfreq 60%
basics
~10 s

Django's test runner swaps in the locmem email backend, which appends every sent message to django.core.mail.outbox. Post to the view under @override_settings(DEFAULT_FROM_EMAIL=...), then assert len(mail.outbox) == 1 and inspect that message.

open as a page

With pytest-django, why does a plain test function that queries a Django model fail with 'Database access not allowed', and how do you fix it?

level: juniorimportance: must knowfreq 55%
basics
~10 s

pytest-django blocks database access unless a test opts in, so an unmarked query raises RuntimeError. Add @pytest.mark.django_db or request the db fixture; the test then runs in a transaction that is rolled back afterwards.

open as a page

Why must DEBUG be False on a production Django site, and what stops working the moment you turn it off?

level: juniorimportance: must knowfreq 80%
basics
~20 s

DEBUG=True shows tracebacks with local variables, request data and most settings to anyone who triggers an error, and keeps a SQL log in memory. Turning it off requires a real ALLOWED_HOSTS, another way to serve static files, and 404/500 templates.

open as a page

Why is Django's runserver command not meant for production, and what serves a Django project there instead?

level: juniorimportance: must knowfreq 70%
basics
~20 s

runserver is a development server: it auto-reloads, runs in one process and was never security-audited or performance-tested. Production runs the project's wsgi.py or asgi.py application object under a real WSGI or ASGI server, usually behind a reverse proxy.

open as a page

In a containerised Django deployment, why does collectstatic run when the image is built while migrate runs once per release before new code takes traffic?

level: middleimportance: must knowfreq 62%
basics
~20 s

collectstatic reads files already in the code and writes them to STATIC_ROOT, so its output belongs in the immutable image. migrate alters the shared database, so it runs once per release, before new-code containers serve requests.

open as a page

What do a Django project's wsgi.py and asgi.py contain, and how does DJANGO_SETTINGS_MODULE decide which settings they load?

level: middleimportance: must knowfreq 55%
basics
~10 s

Each file sets a default DJANGO_SETTINGS_MODULE with os.environ.setdefault and builds a module-level application via get_wsgi_application() or get_asgi_application(). A value already in the environment wins, so each deployment picks its settings without editing the file.

open as a page

How do you run Django management commands such as migrate, collectstatic and createsuperuser non-interactively inside a container?

level: juniorimportance: should knowfreq 48%
basics
~20 s

Pass --noinput (or --no-input) so no command waits for a prompt, give createsuperuser its values through options or DJANGO_SUPERUSER_* environment variables, and rely on the exit status: a failing command exits non-zero and fails the step.

open as a page