Django
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 pageshowhide
guide
overview
~2 minDjango 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`.
- Projects & Settings →
How apps, settings and manage.py fit together, and the path a request takes; every other section assumes this map.
- Model Classes →
Models are the schema the rest of the framework reads and writes, so fields, relations and constraints come early.
- QuerySet API →
How QuerySets compose and when they hit the database; the ORM questions in every other section build on it.
- Views & Responses →
The request-in, response-out contract that routing, class-based views and middleware all wrap.
- Form Processing →
Where submitted data gets validated and saved, and the bridge between views and models.
- 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
- Projects & Settings30 questions
- MTV & the Request Path4 questions
- Apps & AppConfig6 questions
- Per-Environment Configuration4 questions
- CLI Commands & Shell6 questions
- System Checks5 questions
- Release Cadence & Upgrades5 questions
- URL Dispatcher19 questions
- Route Patterns & Converters6 questions
- App Namespaces & Includes4 questions
- Named Routes & Reversing5 questions
- Resolution & Error Handlers4 questions
- Views & Responses24 questions
- Function-Based Handlers4 questions
- HttpRequest Anatomy4 questions
- Reply Classes & Streaming6 questions
- Method & Conditional Decorators5 questions
- Upload Handling5 questions
- Class-Based Views27 questions
- Dispatch Lifecycle4 questions
- Template & Redirect Generics4 questions
- Display Generics4 questions
- Editing Generics5 questions
- Mixins & MRO5 questions
- Paginator & Pages5 questions
- Server-Side Templates27 questions
- Variable Resolution Rules5 questions
- Output Filters4 questions
- Control-Flow & Custom Tags6 questions
- Extends, Blocks & Partials4 questions
- Autoescaping & Safe Strings4 questions
- Engines, Loaders & Context4 questions
- Form Processing27 questions
- Fields & Widgets6 questions
- Cleaning & Error Flow5 questions
- ModelForm Bindings6 questions
- Formsets & Inline Sets5 questions
- Rendering & Bound Fields5 questions
- Model Classes42 questions
- Column Types & Options6 questions
- Relations & Delete Rules6 questions
- Meta Options & Constraints5 questions
- Instance Methods & Saving5 questions
- Table Inheritance Styles6 questions
- Custom Column Types5 questions
- Generated Columns & Keys4 questions
- Content Types & Generic Relations5 questions
- QuerySet API29 questions
- Lazy Evaluation & Result Cache5 questions
- Lookups, Q & F Expressions5 questions
- Create, Update & Delete Calls5 questions
- Aggregation & Annotation5 questions
- Managers & Chainable Filters3 questions
- Raw SQL & Database Functions6 questions
- ORM Query Tuning22 questions
- Related Object Loading5 questions
- Fetch Modes & Deferred Columns4 questions
- Large Result Sets5 questions
- SQL Counting & Inspection4 questions
- Database-Side Computation4 questions
- Databases & Transactions26 questions
- Backends & Connection Settings4 questions
- Atomic Blocks & Savepoints5 questions
- Commit Hooks4 questions
- Row Locking4 questions
- Replicas & Routers4 questions
- PostgreSQL Extras5 questions
- Migration Workflows24 questions
- Autodetector & Apply Commands4 questions
- Scripted Data Changes5 questions
- Conflicts, Merges & Squashing5 questions
- Zero-Downtime Changes5 questions
- Fixtures & Serializers5 questions
- Admin Site27 questions
- Change Lists & Filters5 questions
- Change Forms & Inlines5 questions
- Bulk Actions6 questions
- Staff Rights & Scoping5 questions
- Branding & URL Overrides6 questions
- Accounts & Sign-In26 questions
- Custom User Models4 questions
- Login & Logout Flow5 questions
- Password Hashing & Reset5 questions
- Credential Backends5 questions
- Login-Required Guards3 questions
- Social & MFA Packages4 questions
- Access Rights & Groups17 questions
- Per-Model Codenames4 questions
- Role Assignment4 questions
- Object-Level Checks4 questions
- Enforcement in Views5 questions
- Middleware Components11 questions
- Hook Protocol & Ordering4 questions
- Built-In Stack Order3 questions
- Sync & Async Adapters4 questions
- Sessions & Messages14 questions
- Store Backends & Cookie Flags5 questions
- Flash Notices4 questions
- Signing Utilities5 questions
- Built-In Protections22 questions
- CSRF Tokens & Origins5 questions
- Content Security Policy5 questions
- HTTPS & Security Headers5 questions
- Host Header Validation4 questions
- Secret Key Lifecycle3 questions
- Static & Media Files17 questions
- Asset Collection & Finders4 questions
- Hashed Storage & Manifests4 questions
- WhiteNoise Serving5 questions
- Upload Storage Backends4 questions
- Cache Toolkit16 questions
- Backend Choices & Keys5 questions
- Whole-Page Responses5 questions
- Low-Level Calls & Fragments6 questions
- Async Support14 questions
- Coroutine Views & ASGI5 questions
- Sync Adapters & Thread Safety4 questions
- Coroutine ORM Methods5 questions
- Signals, Tasks & Email21 questions
- Receivers & Dispatch6 questions
- Deferred Work API5 questions
- Celery Wiring5 questions
- Outgoing Mail5 questions
- Translation & Locales20 questions
- Marking Strings6 questions
- Message Catalog Workflow4 questions
- Language Selection5 questions
- Time Zones & Formats5 questions
- Logging & Debugging14 questions
- Handlers & Filters Setup5 questions
- Crash Pages & Error Emails5 questions
- Toolbar & Profilers4 questions
- Test Toolkit26 questions
- Case Class Hierarchy5 questions
- Client & RequestFactory6 questions
- Throwaway Database Setup5 questions
- Plugin Runner Integration5 questions
- Overrides, Outbox & Hooks5 questions
- Running in Production14 questions
- WSGI & ASGI Servers5 questions
- Pre-Launch Checklist4 questions
- Deploy-Time Commands5 questions
questions
556 · 25 sectionsIn Django, what is the difference between a project and an app, and what do startproject and startapp each create?
basics
~20 sA 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.
In Django, why must the runserver development server never serve production traffic, and what serves the application instead?
basics
~10 srunserver 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.
In Django, what does DEBUG=True change, and what must you also set once DEBUG is False in production?
basics
~20 sDEBUG=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.
Django calls itself an MTV framework rather than MVC, so what do its model, template and view do, and where is the controller?
basics
~20 sDjango'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.
In Django, what is AppConfig.ready() for, and what should you avoid doing inside it?
basics
~20 sAppConfig.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.
In Django, what does include() do when a project's urls.py mounts an app's urls.py under a prefix such as 'comments/'?
basics
~20 sinclude() 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.
In Django's path() routes, what do the built-in str, int, slug, uuid and path converters match, and what does the view receive?
basics
~20 sstr (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.
In a Django URLconf listing path('events/<slug:slug>/') before path('events/new/'), which view serves /events/new/, and why?
basics
~20 sThe 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.
In Django, what happens when a view raises Http404, and how does the response differ between DEBUG=True and DEBUG=False?
basics
~20 sRaising 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.
In Django, how do you build the URL of a route named 'job-detail' for job 42 in a view and in a template?
basics
~10 sIn 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/.
In Django, what do require_POST, require_GET, require_safe and require_http_methods do, and what does a request with another method receive?
basics
~10 sThey 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.
In Django, what must a function-based view accept and return, and what happens when it returns None?
basics
~20 sA 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.
In Django, why is request.FILES empty after a user submits a form with a file input, and what must the request look like?
basics
~10 sDjango 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.
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?
basics
~20 sFunction 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".
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?
basics
~20 sFunction 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.
In a Django URLconf, why do you route to MyView.as_view() instead of the class itself, and what does as_view() return?
basics
~20 sDjango'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.
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?
basics
~10 sSet 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.
In a Django function view, how do you paginate a QuerySet with Paginator, and what does the template loop over?
basics
~10 sWrap 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.
In Django, how do you serve a mostly static About page with TemplateView, and how do you add data to its template context?
basics
~10 sRoute 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.
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?
basics
~20 sSet 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().
In Django templates, what does autoescaping do to a {{ review.body }} value, and which characters does it convert?
basics
~20 sDjango'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.
In Django's TEMPLATES setting, what do DIRS and APP_DIRS do, and in what order does Django search for a template name?
basics
~10 sDIRS 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.
In Django templates, how do you apply, chain and pass an argument to a filter, as in {{ invoice.notes|truncatechars:80 }}?
basics
~20 sA 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.
In Django templates, how do {% extends %}, {% block %} and {{ block.super }} work together to build a site-wide page layout?
basics
~20 sA 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.
In Django templates, how does {% for %} work together with {% empty %} and the forloop variable, such as forloop.counter and forloop.last?
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.
In Django forms, what is the difference between a bound and an unbound form, and when does cleaned_data exist?
basics
~20 sA 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.
In Django, what does a ModelForm build from its model, and why must its Meta declare fields or exclude?
basics
~20 sA 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.
In a Django template, what does {{ form }} output by default, and how do you render one field's label, errors and help text yourself?
basics
~20 sSince 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.
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?
basics
~20 sA 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.
With Django's inlineformset_factory, how do you save an order and its line items from one POST so every line references the order?
basics
~20 sBind 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.
In a Django model, what is the difference between null=True and blank=True, and why avoid null=True on a CharField?
basics
~20 snull=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.
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?
basics
~10 sDjango 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).
In a Django model, what is the inner class Meta for, and which options does it typically hold?
basics
~20 sclass 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.
In a Django model, what does a ForeignKey's on_delete argument decide, and how do you choose a value for each relation?
basics
~20 son_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.
How do Django's TextChoices and IntegerChoices work on a model field, and does choices= stop invalid values from reaching the database?
basics
~20 sTextChoices 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.
In Django's ORM, what is the difference between aggregate() and annotate(), and what does each one return?
basics
~10 saggregate() 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.
In Django's ORM, what does it mean that a QuerySet is lazy, and which operations make it actually query the database?
basics
~20 sBuilding 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.
In Django's ORM, what is the difference between filter() and get(), and which exceptions can get() raise?
basics
~10 sfilter() 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.
In Django, when do you use Manager.raw() rather than connection.cursor(), and what does each one give you back?
basics
~20 sManager.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.
A Django dashboard view runs the same SELECT four times; how does the QuerySet result cache explain it, and what fixes it?
basics
~20 sEach 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.
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()?
basics
~20 supdate() 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.
In Django, what do values() and values_list() return instead of model instances, and what do flat=True and named=True change?
basics
~10 svalues() 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.
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?
basics
~10 sstr(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.
In Django's ORM, what do QuerySet.only() and defer() do, and what does reading a deferred field cost you later?
basics
~20 sdefer() 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.
In Django, what does the default autocommit mode mean for a two-wallet transfer, and how does transaction.atomic change it?
basics
~20 sDjango 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.
In Django, what does the DATABASES setting define, and what do you change to move a prototype from SQLite to PostgreSQL?
basics
~20 sDATABASES 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.
In Django, what does transaction.on_commit() do, and why send an order's receipt email through it rather than straight after save()?
basics
~20 stransaction.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.
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()?
basics
~20 sselect_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.
Why can a Django project whose tests all pass on SQLite still break when it runs on PostgreSQL or MySQL in production?
basics
~20 sThe 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.
In Django, what is the difference between makemigrations and migrate, and how does Django know which migrations a database has already applied?
basics
~10 smakemigrations 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.
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?
basics
~20 sBoth 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.
In Django, what do the dumpdata and loaddata management commands do, and where does loaddata look for fixture files?
basics
~20 sdumpdata 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.
In Django, how do you write a data migration that fills new first_name and last_name columns from an existing full_name column?
basics
~20 sCreate 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.
In a Django data migration, why must RunPython code load models with apps.get_model() instead of importing them from models.py?
basics
~20 sapps.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.
How do you register a model with Django's admin, and how do you choose the columns its change list shows?
basics
~10 sRegister 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.
In Django, what do the is_staff and is_superuser user flags each control, and can a superuser without is_staff use the admin?
basics
~20 sis_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.
How do you restrict a Django admin action so only staff holding a custom 'ship order' permission can see and run it?
basics
~10 sPass 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.
How do you add a custom Django admin action that marks the selected orders as shipped, and what does the action function receive?
basics
~10 sWrite 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.
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?
basics
~20 sDefine 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.
In Django's contrib.auth, what is the difference between authenticate() and login(), and why does a sign-in view call both?
basics
~20 sauthenticate() 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.
In Django, how do you restrict a view to signed-in users with login_required or LoginRequiredMixin, and what happens to an anonymous visitor?
basics
~10 sDecorate 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.
In Django, when would you build a custom user model on AbstractUser rather than on AbstractBaseUser with PermissionsMixin?
basics
~20 sSubclass 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.
In Django, how does authenticate() walk the AUTHENTICATION_BACKENDS list, and how does a backend returning None differ from raising PermissionDenied?
basics
~10 sauthenticate() 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.
How would you write a custom Django authentication backend that lets users sign in with their email address and password?
basics
~10 sSubclass 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.
In Django, how do you restrict a function-based view to users holding a given permission, and what happens when they lack it?
basics
~10 sDecorate 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.
In Django's contrib.auth, which permissions does every model get automatically, and how do you check one with has_perm()?
basics
~10 sDjango 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.
In Django, how does a user get permissions through a Group, and how do group grants combine with user.user_permissions?
basics
~20 sA 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.
In Django, how does PermissionRequiredMixin enforce a permission on a class-based view, and how do you customise what a denied user gets?
basics
~10 sPermissionRequiredMixin 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.
In a Django property-listings app, how do you make sure owners can edit only their own listings?
basics
~20 sFetch 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.
What order does Django's startproject MIDDLEWARE list use, and why must SessionMiddleware come before AuthenticationMiddleware?
basics
~10 sSecurity, 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.
How do you write a custom Django middleware, and which part of it runs once versus on every request?
basics
~10 sWrite 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.
How do you write a Django middleware, such as a tenant resolver, that runs in both WSGI and ASGI deployments without an adapter?
basics
~10 sDeclare 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.
In Django, what do a middleware's sync_capable and async_capable attributes declare, and what are their defaults?
basics
~20 sThey 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.
In Django's MIDDLEWARE, where do GZipMiddleware, LocaleMiddleware and CommonMiddleware belong relative to the other built-ins, and why?
basics
~20 sGZipMiddleware 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.
In a Django view, why does appending to a list stored in request.session not persist to the next request?
basics
~20 sDjango 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.
In Django, how do you show a one-time 'Profile saved' notice on the page a user is redirected to?
basics
~10 sCall 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.
In Django's django.core.signing, what does Signer.sign() guarantee about a value, and why can anyone still read the signed result?
basics
~10 sSigner.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.
In Django, which session engines can SESSION_ENGINE select, which is the default, and how do they differ?
basics
~10 sDjango'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.
Using Django's django.core.signing, how would you build an unsubscribe link that expires after 30 days, and handle stale or forged tokens?
basics
~10 sSign the subscriber id with signing.dumps(..., salt=...), which embeds a signed timestamp. The view calls signing.loads(token, salt=..., max_age=timedelta(days=30)), catching SignatureExpired before BadSignature.
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?
basics
~10 sAdd 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.
In a Django template, what does {% csrf_token %} add to a POST form, and why does the submit fail with 403 without it?
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.
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?
basics
~20 sALLOWED_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.
A Django page's fetch() POST returns 403 'CSRF token missing'; how do you send the token correctly instead of exempting the view?
basics
~20 sRead 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.
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?
basics
~10 sThe 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.
In Django, what are STATIC_URL, STATIC_ROOT and STATICFILES_DIRS each for, and why should templates use the {% static %} tag?
basics
~20 sSTATIC_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.
In Django, what is the difference between MEDIA_ROOT and MEDIA_URL, and what does a FileField actually store in the database?
basics
~20 sMEDIA_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.
How do you serve a Django app's static files with WhiteNoise when it runs in a single container with no separate web server?
basics
~10 sInstall 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.
Why does a Django site's CSS load under runserver with DEBUG = True but return 404 as soon as DEBUG is set to False?
basics
~20 sWith 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.
In Django, how does ManifestStaticFilesStorage bust browser caches for static files, and what is stored in staticfiles.json?
basics
~20 sManifestStaticFilesStorage 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.
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?
basics
~20 sDjango'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.
What does Django's cache_page decorator do, and what do its timeout, cache and key_prefix arguments control?
basics
~20 sDjango'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.
A Django weather-forecast site runs on three servers; which built-in cache backend would you pick for its CACHES default, and why?
basics
~20 sPick 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.
Why does Django's LocMemCache backend give inconsistent results once a site runs under several worker processes?
basics
~20 sLocMemCache 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.
How does Django's {% cache %} template tag cache a fragment per user or language, and how do you invalidate that fragment from Python code?
basics
~20 sDjango'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.
In Django's async ORM, which QuerySet calls need an a-prefixed version in an async view, and which can you chain as usual?
basics
~10 sQuerySet 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.
In Django, how do you write an async view, both as a function-based view and as a class-based view?
basics
~20 sDeclare 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.
In Django, what do asgiref's sync_to_async() and async_to_sync() do, and when do you reach for each?
basics
~20 ssync_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.
A Django async view calls three shipping-rate APIs concurrently; what does it gain under WSGI, and what more under ASGI?
basics
~20 sUnder 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.
In Django, why does an async view that calls Invoice.objects.get() raise SynchronousOnlyOperation, and how do you fix it?
basics
~20 sDjango 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.
How do you wire Celery into a Django project, and what goes into celery.py and the project package's __init__.py?
basics
~10 sCreate 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.
In Django, when is send_mail() enough, and when do you build an EmailMessage or EmailMultiAlternatives instead?
basics
~20 ssend_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.
In Django, how would you create a Profile row automatically whenever a new user signs up, using a post_save receiver?
basics
~10 sConnect 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.
A Django post_save receiver keeps a search index in sync, yet some edits never reach it; which ORM calls bypass model signals?
basics
~10 sQuerySet.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.
A Django view creates an order in a transaction and queues a Celery email task that intermittently raises Order.DoesNotExist; what is wrong?
basics
~20 sThe 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.
In Django, how do you mark a user-facing string for translation in Python code and in a template?
basics
~20 sIn 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.
In a Django project with USE_TZ enabled, why use django.utils.timezone.now() instead of datetime.datetime.now()?
basics
~20 sWith 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.
In Django, what do makemessages and compilemessages each do, and why does a project need both .po and .mo files?
basics
~20 smakemessages 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.
In Django, in what order does LocaleMiddleware look for a request's language, and what happens when nothing matches?
basics
~10 sLocaleMiddleware 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.
In Django, why must a model field's verbose_name or a form field's label use gettext_lazy() instead of gettext()?
basics
~20 sModel 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.
In Django, what does a visitor see when a view raises an unhandled exception with DEBUG = True, and what changes with DEBUG = False?
basics
~20 sWith 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.
How does Django apply your LOGGING setting on top of DEFAULT_LOGGING, and why is disable_existing_loggers usually set to False?
basics
~10 sDjango 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.
A Django checkout page takes three seconds locally; how do you use django-debug-toolbar's panels to find where the time goes?
basics
~20 sRead 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.
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?
basics
~20 sDEFAULT_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.
In a Django project, how do you install django-debug-toolbar, and why might it still not appear on your pages?
basics
~20 sAdd 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>.
In Django's test framework, how do SimpleTestCase, TransactionTestCase and TestCase differ, and which one should most tests use?
basics
~20 sSimpleTestCase 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.
In Django testing, what is the difference between the test Client and RequestFactory, and when would you reach for each?
basics
~20 sDjango'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.
When you run Django's manage.py test, which database do the tests use, and what happens to it before and after the run?
basics
~20 sDjango'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.
In a Django TestCase, how do you assert that a sign-up view sends exactly one welcome email from an overridden DEFAULT_FROM_EMAIL?
basics
~10 sDjango'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.
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?
basics
~10 spytest-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.
Why must DEBUG be False on a production Django site, and what stops working the moment you turn it off?
basics
~20 sDEBUG=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.
Why is Django's runserver command not meant for production, and what serves a Django project there instead?
basics
~20 srunserver 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.
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?
basics
~20 scollectstatic 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.
What do a Django project's wsgi.py and asgi.py contain, and how does DJANGO_SETTINGS_MODULE decide which settings they load?
basics
~10 sEach 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.
How do you run Django management commands such as migrate, collectstatic and createsuperuser non-interactively inside a container?
basics
~20 sPass --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.