Back to interview questions

100+ Django Interview Questions and Answers

100+ Django Interview Questions and Answers

Explore 120 Django interview questions and answers on models, forms, queries, transactions, authorization, async work, migrations and deployment.

Explore 120 Django interview questions and answers on models, forms, queries, transactions, authorization, async work, migrations and deployment.

By

Team Sherlock.sh

Add Sherlock as a preferred source on Google

Django interviews should reveal how a candidate turns framework conveniences into reliable application behavior. Hiring teams need evidence of sound request handling, model design, authorization, query construction and transaction boundaries. The strongest candidates can explain why a feature that works for one request may fail when two users submit together or a deployment runs old and new code at the same time.

These 100+ Django Interview Questions and Answers contain 120 questions across beginner, intermediate and experienced levels. They connect Django’s integrated tools with concrete decisions about validation, data consistency, performance, asynchronous work and operations. The API discussion uses Django 6.1 documentation; interviewers should state the project’s actual version and database backend when assessing implementation details.

How can recruiters assess whether a Django candidate understands the guarantees behind a working endpoint?

Present a reservation endpoint that checks availability, saves a booking and queues a confirmation. Ask the candidate to explain concurrent requests, a failed transaction and a timeout after the write. Strong answers separate database constraints from form validation, identify uncertain side effects and propose tests that exercise the actual failure boundary.

Sherlock AI helps hiring teams assess signals of potential AI cheating, deepfakes, impersonation and unauthorized assistance during remote interviews. Combine those signals with a small Django exercise and follow-up changes to the scenario. Evaluate evidence in context rather than treating one signal as conclusive proof of misconduct.

Django Interview Questions

Select questions that match the role’s responsibility for request handling, data, security and deployment. The complete bank appears before the answers, with the same wording and order.

Django Interview Questions for Beginners

Assess the request lifecycle, models, forms, identity and deployment fundamentals.

  1. What does Django provide for a web application?

  2. How does a Django project differ from an app?

  3. What happens between an incoming request and a Django response?

  4. How do models, templates and views divide responsibilities?

  5. What is a URLconf?

  6. Why should applications reverse named URLs?

  7. What is the basic contract of a function-based view?

  8. How do HttpResponse and JsonResponse differ?

  9. When is render useful in a view?

  10. How does Django template inheritance help?

  11. What protection does template autoescaping provide?

  12. What does a Django model class describe?

  13. What is the difference between null and blank on a model field?

  14. How do ForeignKey and ManyToManyField represent relationships?

  15. What does on_delete specify for a ForeignKey?

  16. What is a QuerySet?

  17. How do get and filter differ?

  18. When should get_object_or_404 be used?

  19. How do makemigrations and migrate differ?

  20. What is the Django admin intended for?

  21. How does a Form differ from a ModelForm?

  22. What distinguishes a bound form from an unbound form?

  23. What should be read from cleaned_data?

  24. Why is the post-redirect-get pattern useful?

  25. What does Django's CSRF protection defend against?

  26. How do authentication and authorization differ in Django?

  27. Why must passwords be set through the supported password APIs?

  28. What does a session provide?

  29. How do static files differ from uploaded media?

  30. What does middleware contribute?

  31. Why should production settings disable DEBUG?

  32. What does ALLOWED_HOSTS protect?

  33. Why use timezone-aware datetimes?

  34. What does Django's test client test?

  35. How do TestCase and TransactionTestCase differ?

  36. Why should a list endpoint be paginated?

  37. How does a class-based view become a callable view?

  38. What is a custom management command useful for?

  39. Why should signals be used selectively?

  40. How would you structure a small Django feature?

Django Interview Questions for Intermediate

Explore query behavior, transactions, validation, async boundaries and testing tools.

  1. When does a QuerySet execute, and how does its result cache matter?

  2. How do select_related and prefetch_related avoid repeated queries differently?

  3. How can only and defer introduce unexpected queries?

  4. How do values and values_list change a query's result shape?

  5. When are Q objects useful?

  6. Why use F expressions for some updates?

  7. How do annotate and aggregate differ?

  8. Why does the order of filter and annotate matter?

  9. What should be checked when combining distinct and ordering?

  10. When can get_or_create still produce duplicates?

  11. What does transaction.atomic guarantee?

  12. Why register some work with transaction.on_commit?

  13. Why should database exceptions often be caught outside an atomic block?

  14. When is select_for_update appropriate?

  15. What changes when update is used instead of instance save?

  16. What limitations should be considered before bulk_create?

  17. Why does model save not replace full_clean?

  18. What should a cross-field form clean method do?

  19. What does ModelForm.save(commit=False) require afterward?

  20. How should a form's selectable related objects be restricted?

  21. Why choose a custom user model early?

  22. How should object-level authorization be implemented?

  23. How should mixin ordering be reviewed in class-based views?

  24. What does a middleware short circuit imply?

  25. When does an async Django view provide a benefit?

  26. How should synchronous ORM work be called from async code?

  27. What belongs in a cache key?

  28. How does Vary affect HTTP caching?

  29. How should an upload be validated and stored?

  30. What is the purpose of collectstatic?

  31. Why do data migrations use historical models?

  32. How should a data migration's reverse operation be designed?

  33. How should tests check database-query efficiency?

  34. How does RequestFactory differ from the test client?

  35. Why can a default test client miss CSRF failures?

  36. How should settings changes be isolated in tests?

  37. How should signals be registered reliably?

  38. What does Django's Tasks framework provide and leave to infrastructure?

  39. How should a management command process a large dataset?

  40. How should a reusable Django app avoid project-specific coupling?

Django Interview Questions for Experienced

Examine concurrent writes, schema evolution, isolation, recovery and operational evidence.

  1. How would you introduce a required field without breaking a rolling deployment?

  2. How would you investigate migration drift?

  3. How should concurrent migration branches be reconciled?

  4. How would you enforce a reservation invariant under concurrency?

  5. How should a Django endpoint make repeated write requests idempotent?

  6. What does durable=True add to an atomic block?

  7. How should database deadlocks be handled?

  8. How should a multi-tenant query boundary be designed?

  9. What problems arise when reading from replicas after a write?

  10. How would you debug an N+1 problem that survives prefetching?

  11. How should a slow ORM query be analyzed?

  12. When is keyset pagination preferable to high offsets?

  13. How should cache invalidation coordinate with transactions?

  14. How would you control a cache stampede?

  15. How should an async view react to client disconnection?

  16. What transaction risks accompany a streaming response?

  17. How should persistent database connections be assessed under async serving?

  18. How should request-context data reach background work?

  19. How should secret-key rotation be planned?

  20. How should proxy headers be trusted in a Django deployment?

  21. How would you prevent a personalized response from entering a shared cache?

  22. How should signing differ from encryption in application design?

  23. How should uploaded content be served safely?

  24. How should admin bulk actions preserve business invariants?

  25. What should a custom authentication backend guarantee?

  26. How should a reusable app reference the configured user model in migrations?

  27. How should a large historical backfill be made restartable?

  28. How would you test row-locking behavior correctly?

  29. How can on_commit callbacks be tested inside TestCase?

  30. How should test isolation cover caches and external effects?

  31. How would you upgrade Django with manageable risk?

  32. How should third-party Django packages be evaluated?

  33. How should settings be validated across environments?

  34. How should error monitoring preserve useful context without leaking data?

  35. How should database and file-storage consistency be reconciled?

  36. How should schema rollback differ from application rollback?

  37. How should a background task handle repeated delivery?

  38. How would you diagnose a memory-heavy export endpoint?

  39. How would you design a practical senior Django interview exercise?

  40. What evidence should support a production Django release?

Django Interview Questions and Answers

The answers distinguish framework behavior, database guarantees and application policy. Examples identify their project assumptions so an interviewer can ask for meaningful validation rather than a memorized API call.

Django Interview Questions and Answers for Beginners

These answers connect framework concepts with practical application responsibilities.

1. What does Django provide for a web application?

Django is a Python web framework that brings together request handling, URL routing, templates, database models, forms, authentication and other common application facilities. Its value is a consistent set of conventions and integrated components, not a guarantee that every product decision is already solved.

For a staff scheduling application, Django can provide the model layer and administrative interface while the team defines scheduling rules and permissions. Candidates should distinguish framework facilities from business policy. Installing Django does not automatically provide a production deployment, a safe authorization model or a well-designed database.

2. How does a Django project differ from an app?

A project contains the configuration and composition of a particular site or service, while an app groups a coherent area of functionality. A project can include several apps, and a well-designed app may be reusable across projects.

An inventory project might include catalogue, purchasing and reporting apps. Split around meaningful responsibilities rather than creating one app for every model or putting all behavior in a single enormous app. An app boundary is a code-organization decision; it does not automatically create a separate database, process or security boundary.

3. What happens between an incoming request and a Django response?

The server passes a request into Django's configured stack, middleware participates in processing, URL resolution selects a view, and the view produces a response. Templates and database queries may be involved, but a view can also return a simple response without either.

Trace a failing endpoint through those stages instead of assuming every error originates in the view. Middleware can return early, and exceptions or response processing can change the path. Understanding the lifecycle helps locate authentication, logging and transaction behavior in the right place.

4. How do models, templates and views divide responsibilities?

Models represent application data and related behavior, templates describe presentation, and views coordinate handling a request and returning a response. Django's terminology does not imply that a view should contain every business rule or that a template should query and mutate data freely.

For an order page, a view can obtain an authorized order and render a template, while a separate operation handles placing the order. Keep the division understandable and testable. The useful interview answer explains who owns decisions and side effects rather than arguing only about whether the pattern is called MTV or MVC.

5. What is a URLconf?

A URLconf defines mappings from URL patterns to view callables. Django resolves patterns in order, so a broad earlier route can prevent a later, more specific route from being selected.

Use path converters for expected route values and give routes meaningful names. An integer converter can reject a noninteger path segment before the view, but it does not establish that the referenced object exists or belongs to the requester. Routing validation and resource authorization remain separate responsibilities.

6. Why should applications reverse named URLs?

Reversing a named URL constructs a path from the routing configuration instead of scattering hard-coded paths through views and templates. This makes route changes easier to maintain and lets parameters be handled consistently.

For example, a detail link can refer to an order-detail name and its identifier. Namespaces help distinguish similarly named routes in different apps. Reversal can fail when a name or argument does not match the configured route, so test important links rather than assuming a string that looks plausible points to the intended view.

7. What is the basic contract of a function-based view?

A function-based view accepts a request and any resolved URL arguments, then returns a response or raises an exception that Django handles appropriately. It should enforce the endpoint's method, input and authorization contract before performing side effects.

A health endpoint can return a small JsonResponse, while an edit endpoint may bind a form and redirect after success. Avoid returning arbitrary Python values and expecting Django to infer the entire HTTP contract. Status codes, content type and failure behavior should be deliberate.

from django.http import JsonResponse
from django.views.decorators.http import require_GET

@require_GET
def health(request):
    return JsonResponse({'status': 'ok'})

# Register health in the project's URLconf.
# This is process liveness, not a database/readiness check.
from django.http import JsonResponse
from django.views.decorators.http import require_GET

@require_GET
def health(request):
    return JsonResponse({'status': 'ok'})

# Register health in the project's URLconf.
# This is process liveness, not a database/readiness check.
from django.http import JsonResponse
from django.views.decorators.http import require_GET

@require_GET
def health(request):
    return JsonResponse({'status': 'ok'})

# Register health in the project's URLconf.
# This is process liveness, not a database/readiness check.

8. How do HttpResponse and JsonResponse differ?

HttpResponse represents a general HTTP response body and headers. JsonResponse serializes suitable Python data as JSON and sets the corresponding content type, with a dictionary required by default unless safe=False is explicitly chosen.

Use a dictionary response to make fields such as status and result clear. JSON serialization does not authorize the data being returned or make internal model objects a suitable public contract. Select fields intentionally, handle values the encoder cannot represent and avoid exposing secrets through a convenient dump of an object's attributes.

9. When is render useful in a view?

render combines a template with a context and returns an HTTP response. It keeps the common template-response path concise while allowing the view to supply the data needed for presentation.

A catalogue view can pass an authorized, suitably bounded product list into a template. Keep expensive work and hidden database access visible during review; a short render call does not prove the page is cheap. Templates should receive clear values rather than an unrestricted object graph whose properties unexpectedly trigger queries.

10. How does Django template inheritance help?

Template inheritance lets a base template define shared structure and named blocks that child templates fill or extend. It supports consistent page layout without copying the entire header, navigation and footer into every template.

Use includes for reusable fragments and inheritance for the overall structure. Keep block names and ownership clear so a child template does not accidentally omit required content. Reuse should reduce duplication without creating a chain of overrides so deep that a reviewer cannot determine the final rendered page.

11. What protection does template autoescaping provide?

Autoescaping encodes characters in ordinary template values for the HTML context, reducing a common route to script injection. It is a contextual protection, not a universal sanitizer for every language or browser sink.

Do not mark untrusted content safe merely to remove visible escaping. JavaScript, URLs, CSS and intentionally allowed rich HTML need their own appropriate handling. A candidate should explain where the value is inserted and why the chosen encoding is suitable, rather than claiming that using Django templates makes all output safe automatically.

12. What does a Django model class describe?

A model class describes fields and relationships and provides an interface to stored records through the ORM. Its metadata can also express indexes, constraints and other persistence choices.

A Booking model might link a customer and a resource and record a start time. The model definition still needs a migration to change an existing database schema. Also distinguish Python validation from database enforcement: a rule expressed in application code is not automatically enforced for every possible database writer.

13. What is the difference between null and blank on a model field?

null concerns whether the database can store SQL NULL for a field, while blank concerns validation allowing an empty value. Their purposes differ, even though both can appear to relate to missing information.

For string fields, allowing both an empty string and NULL can create two representations of absence unless there is a specific reason and backend consideration. Decide what missing means for the domain and test forms, direct model operations and queries consistently. Setting blank=True does not make a nonnullable database column accept NULL.

Option

Primary concern

Does not establish

null

Database NULL storage

Form-level optionality

blank

Validation of empty input

Database acceptance of NULL

14. How do ForeignKey and ManyToManyField represent relationships?

A ForeignKey represents a many-to-one relationship, while a ManyToManyField represents associations through an intermediate table. The choice should follow the data's cardinality and the information carried by the relationship.

An order belongs to one customer, while a course may have many students and each student many courses. If enrollment has its own status or timestamp, an explicit through model can represent that information. A relationship field does not decide which users may traverse or edit the related records.

15. What does on_delete specify for a ForeignKey?

on_delete specifies Django's behavior when the referenced object is deleted, such as cascading deletion or preventing it while references exist. It should express a deliberate lifecycle policy for the relationship.

Deleting a customer might be prohibited while retained invoices reference it, rather than cascading away financial history. Review the actual deletion path and database behavior; Django's on_delete setting should not be casually described as a database-level ON DELETE clause generated for every case. Test the consequences with representative related records.

16. What is a QuerySet?

A QuerySet represents a database query and its potential results. It can be filtered and composed before evaluation, which allows Django to construct the eventual query rather than immediately loading every matching row.

Treat it as a query object with an execution lifecycle, not merely a Python list. Iteration, conversion and certain other operations can execute it. Passing a QuerySet into a helper or template can therefore move database work to a less obvious location, affecting latency, exceptions and resource usage.

17. How do get and filter differ?

get expects exactly one matching object and raises a model-specific exception when none or more than one match. filter returns a QuerySet that can contain zero, one or many results.

Use get when uniqueness is part of the contract and filter when a collection is intended. Replacing get with first just to suppress a multiple-match failure can hide a broken invariant. Where uniqueness matters under concurrent writes, enforce it at the database level rather than relying only on the query method chosen by the reader.

18. When should get_object_or_404 be used?

get_object_or_404 converts an expected missing-object condition into an HTTP 404 while preserving the normal object lookup behavior. It is useful at a request boundary where absence should be presented as not found.

Pass a QuerySet already restricted to the requester's permitted scope when appropriate. Looking up an object by primary key and rendering it before checking ownership creates a disclosure risk that the helper does not solve. A 404 helper also does not turn a multiple-result lookup into a unique one.

19. How do makemigrations and migrate differ?

makemigrations creates migration files describing model-state changes, while migrate applies the migration graph to a database. Generating a file does not alter the deployed schema by itself.

Commit and review migration files with the code that requires them, then apply the intended files through the deployment process. Do not generate unrelated migrations independently on every production instance. Inspect data impact and backend behavior because a small-looking model edit can require a costly table operation.

20. What is the Django admin intended for?

The admin provides a model-oriented interface for trusted staff to manage application data. It can accelerate internal workflows, but it is not automatically the right customer-facing interface or a complete business-process engine.

Configure displayed fields, search, filters and permissions for the actual staff task. A bulk action or editable field can bypass assumptions made by a custom public view, so administrative writes need the same important invariants. Staff access should remain narrow and auditable rather than being granted merely because a user needs one management screen.

21. How does a Form differ from a ModelForm?

A Form defines input fields and validation independently of a particular model. A ModelForm derives selected fields and model-related validation from a model and can help create or update an instance.

Use a plain form for a search or multi-step operation whose input is not one model row. For a ModelForm, explicitly allow the editable fields so a newly added sensitive model field does not become writable accidentally. Neither type decides authorization or whether the requested business transition is permitted.

22. What distinguishes a bound form from an unbound form?

A bound form has supplied data to validate and render, while an unbound form represents an initial or empty presentation. Boundness depends on supplying data, not on whether that data contains nonempty values.

An empty POST should still bind the form and produce required-field errors. A common mistake is using truthiness to replace an empty submitted dictionary with None, turning invalid submitted data into an unbound form. Keep the request-method decision explicit so redisplayed errors correspond to what the user actually submitted.

# In a view, after importing the application's BookingForm:
# if request.method == 'POST':
#     form = BookingForm(request.POST)
# else:
#     form = BookingForm()

# Standalone demonstration of the empty-submission distinction:
def form_data_for_method(method, posted_data):
    return posted_data if method == 'POST' else None

empty_submission = {}
assert form_data_for_method('POST', empty_submission) is empty_submission
assert form_data_for_method('GET', empty_submission) is None
# No Django form is constructed by this standalone example.
# In a view, after importing the application's BookingForm:
# if request.method == 'POST':
#     form = BookingForm(request.POST)
# else:
#     form = BookingForm()

# Standalone demonstration of the empty-submission distinction:
def form_data_for_method(method, posted_data):
    return posted_data if method == 'POST' else None

empty_submission = {}
assert form_data_for_method('POST', empty_submission) is empty_submission
assert form_data_for_method('GET', empty_submission) is None
# No Django form is constructed by this standalone example.
# In a view, after importing the application's BookingForm:
# if request.method == 'POST':
#     form = BookingForm(request.POST)
# else:
#     form = BookingForm()

# Standalone demonstration of the empty-submission distinction:
def form_data_for_method(method, posted_data):
    return posted_data if method == 'POST' else None

empty_submission = {}
assert form_data_for_method('POST', empty_submission) is empty_submission
assert form_data_for_method('GET', empty_submission) is None
# No Django form is constructed by this standalone example.

23. What should be read from cleaned_data?

cleaned_data contains values that have passed the form's relevant cleaning steps, often converted into useful Python types. It should be used after validation rather than treating raw request strings as already trustworthy domain values.

A date field can supply a date object and a numeric field can reject malformed input. Cross-field rules still need explicit cleaning, and fields with errors may not be present as expected. Validation establishes an input contract; permission checks and database concurrency constraints remain separate.

24. Why is the post-redirect-get pattern useful?

After a successful state-changing POST, redirecting to a GET page avoids the ordinary browser refresh behavior that can resubmit the same form. It also gives the result a useful navigable URL.

For a created booking, redirect to its detail page after the operation succeeds. This pattern improves navigation but is not a complete duplicate-prevention mechanism: two clicks or retried network requests can still reach the server. Important writes need their own uniqueness or idempotency rules in addition to the redirect.

25. What does Django's CSRF protection defend against?

CSRF protection helps prevent another site from causing a user's browser to submit an unwanted authenticated action using ambient credentials. Django's mechanism combines request checks and token handling for protected unsafe requests.

Include the appropriate token in forms and handle supported AJAX submission correctly. Do not disable protection simply because an endpoint returns JSON. CSRF protection does not replace authentication, object authorization or protection against script injection running within the trusted origin.

26. How do authentication and authorization differ in Django?

Authentication establishes who the requester is, while authorization determines what that requester may do. Django's user, group and permission facilities help implement these concerns, but application-specific resource rules still need to be designed.

A logged-in employee may view their own expense report without being allowed to approve it or see every colleague's report. Check the requested operation and object scope, not just is_authenticated. Successful login is not blanket permission to access every primary key supplied in a URL.

27. Why must passwords be set through the supported password APIs?

Django's password APIs apply the configured password hashing and verification behavior. Assigning a raw password directly to the stored password field does not perform the intended hashing workflow.

Use set_password or appropriate user-creation helpers and authenticate through the configured system. Password validation and password hashing are distinct concerns, so ensure the relevant creation or reset flow applies both as needed. Never use a reversible encoding or a plain comparison as a replacement for the supported password storage contract.

28. What does a session provide?

A session associates state with a sequence of requests using a configured backend and a session identifier or signed representation. The exact storage and trust properties depend on that backend.

A shopping flow can retain a small identifier for a cart, while the authoritative cart contents remain in a database. Keep session payloads bounded and avoid assuming that every backend encrypts data or supports immediate revocation identically. Session expiration and logout behavior should be tested for the selected backend and application policy.

29. How do static files differ from uploaded media?

Static files are application assets such as stylesheets and scripts, while uploaded media originates from users or other external inputs and follows a different lifecycle and trust model. They should not be handled as interchangeable directories.

A deployment can collect versioned application assets while storing uploads in a dedicated storage service. Uploaded content needs access control, validation and safe serving behavior. A filename ending in an image extension is not proof that the content is safe or that it should be publicly accessible.

30. What does middleware contribute?

Middleware wraps or participates in request and response processing for concerns that apply across views, such as sessions or security headers. Its ordering affects which information is available and how responses travel back through the stack.

Authentication middleware depends on the appropriate session setup, for example. Keep application-specific business transactions in a place where their ownership is clear rather than hiding every decision in middleware. A middleware component may return a response without calling the next layer, so downstream code is not guaranteed to run.

31. Why should production settings disable DEBUG?

DEBUG enables development-oriented behavior and detailed error information that should not be exposed in production. Turning it off is necessary, but it is only one part of configuring a deployed application safely.

Configure error reporting, allowed hosts, secrets, HTTPS handling and static assets for the actual environment. A site that merely hides its traceback can still have broken authorization or leak data through logs. Verify the production settings through deployment checks and representative requests rather than relying on a single Boolean.

32. What does ALLOWED_HOSTS protect?

ALLOWED_HOSTS constrains the hostnames Django accepts through its host-validation path, helping prevent attacks that exploit an untrusted Host value. It should match the application's intended hostnames and proxy configuration.

Do not populate it with a wildcard just to silence a deployment error without understanding the exposure. Use Django's supported host access rather than bypassing checks with raw header reads. This setting is not a network firewall and does not determine which users are authorized to use the site.

33. Why use timezone-aware datetimes?

Aware datetimes identify their offset context and help represent instants consistently across storage and presentation. With timezone support enabled, applications should use the appropriate Django timezone utilities and distinguish instants from local business dates.

A meeting scheduled for a user's local time needs a deliberate timezone and a policy for daylight-saving ambiguity. Simply attaching a label to a naive datetime can misinterpret the original value. Test transitions and interchange formats rather than assuming every local day has the same duration.

34. What does Django's test client test?

The test client sends simulated requests through Django's testing machinery and lets tests inspect responses, templates and other behavior. It is useful for application-level request handling without starting a live browser.

Use it to verify a permission denial or a redirect after a valid form submission. It does not prove that JavaScript works, the reverse proxy is configured correctly or a real browser enforces the intended cookie behavior. Tests should state the boundary they exercise and complement it with integration or browser tests where needed.

35. How do TestCase and TransactionTestCase differ?

TestCase uses transactional isolation techniques that make many database tests efficient, while TransactionTestCase permits tests that need to observe actual transaction behavior more directly. Their setup and cleanup behavior differs.

A test of commit hooks or locking may need the latter or a specific supported testing helper. Do not choose solely by which class is faster. A test can pass under TestCase's surrounding transaction while failing in the application's normal autocommit context, so match the test environment to the behavior being asserted.

36. Why should a list endpoint be paginated?

Pagination bounds the data returned and the work needed to render or transfer it. Returning every record becomes slow and memory-intensive as the dataset grows, even if the first development fixture is tiny.

Define a stable ordering and a maximum page size, then handle invalid or empty page requests consistently. Pagination also needs authorization before counting or selecting results. Offset pagination can become expensive or unstable under concurrent changes, so its suitability depends on scale and the navigation contract.

37. How does a class-based view become a callable view?

A class-based view exposes a callable through as_view, which creates the appropriate per-request view instance and dispatches to handlers such as get or post. The URLconf uses that callable rather than an arbitrary class object.

Generic views can remove repetitive code, but candidates should understand which methods are extension points and when their code runs. Avoid placing mutable per-request data in shared class attributes. A short subclass can still have complex inherited behavior, so inspect the method-resolution path when customizing it.

38. What is a custom management command useful for?

A management command provides a supported entry point for operational or maintenance work within the Django project environment. It can share application code and settings without pretending to be an HTTP endpoint.

A reconciliation command should have explicit arguments, useful output, failure exit behavior and a policy for repeated execution. Avoid putting important work directly at import time. Commands that modify data need the same transaction, authorization-of-operator and audit considerations as other administrative workflows.

39. Why should signals be used selectively?

Signals decouple a sender from receivers, which can be useful for framework integration or optional reactions. They can also make execution harder to follow when important business behavior happens through hidden receivers.

For an order workflow, an explicit service call often makes the transaction and side effects clearer than a chain of save signals. If signals are used, define registration, lifetime and repeated-delivery behavior. Do not assume that every bulk ORM operation calls model save or emits the same signals as an instance save.

40. How would you structure a small Django feature?

Start with the user operation, data constraints and authorization rules, then connect models, forms, views, templates and URLs around that contract. Keep external effects and persistence ownership explicit enough to test.

For a reservation feature, test a valid request, invalid input, an unauthorized requester and a conflicting reservation. Add only the abstractions that clarify those behaviors. A feature is not complete merely because the happy-path page renders; it also needs a migration and deployment plan appropriate to its data changes.

Django Interview Questions and Answers for Intermediate

These answers explain concrete implementation choices and their failure cases.

41. When does a QuerySet execute, and how does its result cache matter?

A QuerySet usually defers its database query until an operation requires results. Evaluation can populate that QuerySet's result cache, but constructing a new filtered QuerySet does not mean it reuses a previously loaded collection as an in-memory filter.

A view that evaluates a queryset and then repeatedly creates new related queries can still perform substantial database work. Identify the exact objects being evaluated and measure query counts for representative data. Reusing a cache also means reusing an earlier observation, so do not treat it as automatically refreshed after another transaction changes the database.

# Project context: Product is an application model with an active field.
def active_product_ids(Product):
    queryset = Product.objects.filter(active=True).order_by('pk')
    # The list conversion below evaluates the values query.
    return list(queryset.values_list('pk', flat=True))

# The returned list is a materialized observation, not a live query.
# Project context: Product is an application model with an active field.
def active_product_ids(Product):
    queryset = Product.objects.filter(active=True).order_by('pk')
    # The list conversion below evaluates the values query.
    return list(queryset.values_list('pk', flat=True))

# The returned list is a materialized observation, not a live query.
# Project context: Product is an application model with an active field.
def active_product_ids(Product):
    queryset = Product.objects.filter(active=True).order_by('pk')
    # The list conversion below evaluates the values query.
    return list(queryset.values_list('pk', flat=True))

# The returned list is a materialized observation, not a live query.

42. How do select_related and prefetch_related avoid repeated queries differently?

select_related follows suitable single-valued relationships using SQL joins, while prefetch_related performs separate lookups and combines related results in Python. Prefetching can handle relationships such as many-to-many that would multiply rows in a simple joined object result.

Choose based on the relationship and the data needed by the page. Loading every related object can consume more memory than the repeated-query problem it replaces. Inspect the actual access pattern: applying a different related filter later may issue a new query rather than use the prefetched result as expected.

Method

Typical relationship

Main trade-off

select_related

Foreign key or one-to-one

Joined row width and join work

prefetch_related

Collections or custom related query

Extra queries and Python-side memory

43. How can only and defer introduce unexpected queries?

These methods defer loading selected model fields until they are accessed. They can reduce initial data transfer, but each later access to deferred information may require another query.

A list page that never uses a large text field can benefit, while a template that reads that field for every row can create a new query pattern. Measure the rendered request rather than only the initial ORM call. Deferred-field access also has async-context limitations, so fetch the fields needed before entering a path where synchronous database work is not allowed.

44. How do values and values_list change a query's result shape?

values returns dictionaries for selected fields, while values_list returns tuple-like selected values, with options for a flat single-field result. They avoid constructing full model instances when those instances are unnecessary.

A reporting endpoint can select identifiers and totals explicitly, reducing work and clarifying its output contract. Relationships can still multiply rows, and selected fields do not automatically imply distinct business entities. Review joins, ordering and aggregation together so a compact projection does not silently change the meaning of the result set.

45. When are Q objects useful?

Q objects express composable query conditions, including OR and negation, beyond the implicit AND of ordinary keyword filters. They are useful when a search or policy requires a grouped Boolean condition.

For example, a catalogue may allow matches by name or SKU while still requiring the item to belong to the permitted tenant. Parenthesize the logic deliberately and keep authorization restrictions outside user-controlled alternatives. A syntactically valid OR expression can accidentally broaden access if the tenant condition applies to only one branch.

from django.db.models import Q

# Product has tenant_id, name and sku fields.
def matching_products(Product, tenant_id, term):
    return Product.objects.filter(tenant_id=tenant_id).filter(
        Q(name__icontains=term) | Q(sku__iexact=term)
    )

# tenant_id must come from the authorized request scope.
# Bound input length and pagination at the endpoint.
from django.db.models import Q

# Product has tenant_id, name and sku fields.
def matching_products(Product, tenant_id, term):
    return Product.objects.filter(tenant_id=tenant_id).filter(
        Q(name__icontains=term) | Q(sku__iexact=term)
    )

# tenant_id must come from the authorized request scope.
# Bound input length and pagination at the endpoint.
from django.db.models import Q

# Product has tenant_id, name and sku fields.
def matching_products(Product, tenant_id, term):
    return Product.objects.filter(tenant_id=tenant_id).filter(
        Q(name__icontains=term) | Q(sku__iexact=term)
    )

# tenant_id must come from the authorized request scope.
# Bound input length and pagination at the endpoint.

46. Why use F expressions for some updates?

F expressions let the database refer to a field's current value within an expression, which can avoid a lost update caused by reading a value into Python and writing back a computed replacement. The database performs the relevant expression as part of the statement.

For a counter, an update using F('count') + 1 avoids two callers both writing the same locally calculated increment. It does not make a multi-step business operation atomic or enforce an upper bound by itself. Combine conditional predicates, constraints or a transaction strategy when the invariant is wider than one expression.

from django.db.models import F

# Stock has an integer available field and a nonnegative DB constraint.
def reserve_one(Stock, stock_id):
    changed = Stock.objects.filter(
        pk=stock_id, available__gte=1
    ).update(available=F('available') - 1)
    return changed == 1

# This covers one conditional stock update only.
# An order plus inventory operation needs a wider transaction contract.
from django.db.models import F

# Stock has an integer available field and a nonnegative DB constraint.
def reserve_one(Stock, stock_id):
    changed = Stock.objects.filter(
        pk=stock_id, available__gte=1
    ).update(available=F('available') - 1)
    return changed == 1

# This covers one conditional stock update only.
# An order plus inventory operation needs a wider transaction contract.
from django.db.models import F

# Stock has an integer available field and a nonnegative DB constraint.
def reserve_one(Stock, stock_id):
    changed = Stock.objects.filter(
        pk=stock_id, available__gte=1
    ).update(available=F('available') - 1)
    return changed == 1

# This covers one conditional stock update only.
# An order plus inventory operation needs a wider transaction contract.

47. How do annotate and aggregate differ?

annotate adds calculated information associated with each result or grouping, while aggregate returns a summary result for the queryset. The grouping and joins determine what is actually counted or summed.

A department list might annotate each department with employee count, while a dashboard might aggregate a total across all employees. Inspect SQL when several relationships are involved because joins can multiply rows and inflate a calculation. Naming a result total does not prove that its grouping matches the business definition.

48. Why does the order of filter and annotate matter?

Filtering before or after annotation can change which rows contribute to a calculation and which calculated results are retained. These operations are not generally interchangeable.

A report asking for departments with at least five active employees differs from one annotating all employees and then filtering departments that happen to have an active employee. Write the intended population in plain language, construct a small fixture with contrasting cases and inspect the generated query. A plausible count on uniform sample data can conceal the wrong operation order.

49. What should be checked when combining distinct and ordering?

Ordering fields can participate in the selected SQL columns and affect whether rows are considered distinct. Related-model ordering can therefore produce apparent duplicates even when the selected application fields look identical.

A query selecting customer IDs while ordering by related events needs an explicit definition of which event determines the order. Do not add distinct mechanically until the output happens to look right. Review backend-specific distinct options and use a query structure that expresses one row per intended entity with a deterministic ordering rule.

50. When can get_or_create still produce duplicates?

Its concurrency safety depends on the database enforcing uniqueness for the lookup that is meant to identify one object. Without that constraint, concurrent callers can both fail to find a row and each create one.

For an external event identifier, define the appropriate unique constraint and handle the resulting conflict according to the operation's contract. Defaults supply creation values but do not change the identity lookup. Also avoid using get_or_create from a safe GET endpoint to perform hidden writes; method semantics and database uniqueness solve different concerns.

51. What does transaction.atomic guarantee?

atomic defines a database transaction boundary or nested savepoint behavior for the selected connection. Changes inside the successful outer transaction commit together, while an exception can trigger rollback of the relevant scope.

Keep the transaction focused on the database invariant and avoid waiting on slow external services while holding locks. It does not roll back email, object storage or an already completed remote API call. Python object attributes also do not automatically revert when the database transaction rolls back, so reconcile in-memory state before reusing it.

52. Why register some work with transaction.on_commit?

on_commit delays a callback until the enclosing transaction successfully commits, preventing work such as sending a notification for a row that later rolls back. Without an active transaction, the callback follows the documented immediate behavior.

A task that reads a newly created record should not race ahead before that record is committed. However, a process can fail after commit and before or during the callback, so on_commit alone is not durable delivery. Use a transactional outbox or another appropriate mechanism when the follow-up action must survive that gap.

Mechanism

Benefit

Remaining gap

Immediate callback

Simple execution

May run before transaction commits

on_commit

Runs after successful commit

Process failure can lose follow-up

Transactional outbox

Durable pending record with business write

Delivery still needs retry/idempotency

53. Why should database exceptions often be caught outside an atomic block?

A database error can leave the transaction in a broken state until rollback occurs. Catching the error inside the same atomic scope and continuing to query can hide the failure from the transaction manager and cause further transaction errors.

Place an inner atomic block around the operation that may fail and catch the expected exception outside that inner block when recovery is appropriate. This lets the savepoint rollback finish before further work. Do not treat this pattern as permission to ignore every integrity failure; understand which constraint failed and whether the remaining operation is valid.

54. When is select_for_update appropriate?

select_for_update locks selected rows for a transaction according to the database backend's supported behavior. It can coordinate read-modify-write operations when competing transactions must not change the same protected rows concurrently.

Use it inside an appropriate transaction and keep the locked interval short. Backend support and options differ, and a missing row cannot always be protected by pretending it was selected. Test with the production database and real competing connections; SQLite behavior or a single-threaded unit test does not establish the intended locking guarantee.

55. What changes when update is used instead of instance save?

QuerySet.update performs a database-level update without calling each model instance's save method or the corresponding save signals. It can be efficient and useful for expression-based updates, but bypasses behavior attached to those instance hooks.

If a business invariant exists only in an overridden save method, a bulk update may violate it. Put critical enforceable constraints in the database and route application operations through explicit logic where needed. Review affected-row semantics and stale in-memory objects after the update instead of assuming every loaded instance changes automatically.

56. What limitations should be considered before bulk_create?

bulk_create reduces per-object insertion overhead but has documented differences from saving each instance, including save-hook and signal behavior and backend-dependent handling of generated values or conflict options. It should be selected with those contracts in mind.

A large import can validate records in batches and then insert them efficiently. Define what happens to invalid or conflicting rows and whether related data needs a separate step. Do not use the method merely because it is faster in a tiny benchmark while relying on side effects it intentionally does not run.

57. Why does model save not replace full_clean?

Saving a model does not automatically run the complete model-validation workflow. full_clean performs validation steps that are useful at an application boundary, while the database independently enforces its own constraints.

A service creating a model directly must decide how to validate input rather than assuming that a successful save proves every application rule was checked. Even a prior uniqueness validation can race another writer, so retain database constraints and handle conflicts. Validation improves feedback; it does not replace transactional enforcement.

58. What should a cross-field form clean method do?

A form's clean method should evaluate relationships among already cleaned values, tolerate fields that failed their own validation, and report errors at the appropriate field or form level. It should preserve the superclass cleaning behavior when required by the form type.

For a date range, compare the endpoints only when both are present and valid, then attach a useful error if the end precedes the start. Do not access raw strings as if they were converted dates. Keep side effects out of ordinary validation so repeated rendering or validation does not create records or send messages.

from django import forms

class DateRangeForm(forms.Form):
    start = forms.DateField()
    end = forms.DateField()

    def clean(self):
        cleaned = super().clean()
        start, end = cleaned.get('start'), cleaned.get('end')
        if start is not None and end is not None and end < start:
            self.add_error('end', 'End must not precede start.')
        return cleaned

# Use within a configured Django application; no writes occur in clean.
from django import forms

class DateRangeForm(forms.Form):
    start = forms.DateField()
    end = forms.DateField()

    def clean(self):
        cleaned = super().clean()
        start, end = cleaned.get('start'), cleaned.get('end')
        if start is not None and end is not None and end < start:
            self.add_error('end', 'End must not precede start.')
        return cleaned

# Use within a configured Django application; no writes occur in clean.
from django import forms

class DateRangeForm(forms.Form):
    start = forms.DateField()
    end = forms.DateField()

    def clean(self):
        cleaned = super().clean()
        start, end = cleaned.get('start'), cleaned.get('end')
        if start is not None and end is not None and end < start:
            self.add_error('end', 'End must not precede start.')
        return cleaned

# Use within a configured Django application; no writes occur in clean.

59. What does ModelForm.save(commit=False) require afterward?

commit=False returns an unsaved instance so the caller can set server-controlled values before saving. For forms with many-to-many data, the caller may need to save the instance and then call save_m2m to persist those relationships.

An article form can exclude author from editable fields and assign the authenticated user in trusted code. This does not authorize every related object chosen by the form; restrict those querysets too. If the complete operation must be atomic, include the instance and relationship writes in a suitable transaction.

60. How should a form's selectable related objects be restricted?

Limit the field's queryset to objects the requester may select and revalidate the business operation on submission. A hidden option in the rendered interface is not a server-side permission check.

For a project task form, expose only projects in the requester's allowed organization. Bind the requester through an explicit form initialization contract rather than storing it in shared global state. Test a forged identifier from another organization and a permission change between display and submission.

61. Why choose a custom user model early?

Changing the user model after tables and relationships exist can be difficult because it affects migrations, foreign keys and authentication assumptions. Choosing an appropriate custom model at project start preserves flexibility for identity requirements.

Use the supported swappable-user references in models and obtain the configured user model where needed instead of hard-coding the default class throughout the application. A custom model does not mean every profile field belongs on the authentication entity. Keep identity, permissions and domain profile data separated when their lifecycles differ.

62. How should object-level authorization be implemented?

Define the rule for the particular object and action, then enforce it on every access path, including list queries, detail views, forms and background operations. Django's general permission facilities do not automatically implement every tenant or ownership policy.

A manager may edit reports within one department but only read reports in another. Scope the query and validate the action rather than loading arbitrary objects and relying on a template to hide buttons. Test both direct identifiers and indirect relationship choices, because authorization bugs often appear outside the main detail page.

63. How should mixin ordering be reviewed in class-based views?

Python's method-resolution order determines how mixin methods compose, so ordering can affect authentication, dispatch and extension hooks. A mixin must cooperate with the intended superclass calls rather than silently replacing the rest of the chain.

Review the actual method being overridden and test unauthorized and invalid requests, not only a successful response. Avoid adding several convenience mixins without understanding their contracts. When the inheritance chain becomes hard to explain, a simpler view with explicit helper calls may be easier to maintain.

64. What does a middleware short circuit imply?

A middleware can return a response without invoking the next callable, so later middleware and the view may never run for that request. Response processing then unwinds through the middleware layers that were entered.

A maintenance-mode response is a common example. Logging, security headers and cleanup should be placed with this behavior in mind so early responses still receive the necessary treatment. Do not assume that a hook in a later layer observes every request simply because the component appears in the settings list.

65. When does an async Django view provide a benefit?

An async view can help coordinate suitable nonblocking I/O, especially under an ASGI stack that preserves asynchronous processing. It does not make CPU-bound Python work faster or automatically convert synchronous dependencies into nonblocking operations.

A view calling several independent async services may reduce waiting time, but it still needs deadlines, bounded concurrency and failure handling. Sync middleware or libraries can introduce adaptation and thread usage. Measure the complete deployed stack rather than assuming that adding async def changes its capacity in a predictable way.

66. How should synchronous ORM work be called from async code?

Use supported asynchronous ORM methods where they fit, or isolate a synchronous operation behind the documented sync-to-async boundary. Do not call async-unsafe synchronous database code directly in an event-loop context and disable protections to make the error disappear.

Django 6.1 does not support transactions in async mode, so express a transactional unit of work as one synchronous function called through the supported sync-to-async adapter. Keep connection-sensitive work within the appropriate boundary rather than passing database handles between threads. Confirm the current async transaction capabilities before designing around them.

67. What belongs in a cache key?

A cache key must distinguish every input that can change the cached result, including relevant tenant, user-permission scope, language, version and query parameters. Omitting one can return incorrect data or disclose another user's result.

A public product summary can have a broader key than a staff-only report. Normalize input deliberately and bound key size, but do not collapse distinct authorization scopes for convenience. Also define how changes invalidate or expire the entry; a carefully named key with no update policy can still serve stale decisions.

import hashlib
import json

def report_cache_key(tenant_id, permission_revision, language, filters):
    # Caller supplies a validated, JSON-serializable filter mapping.
    payload = [tenant_id, permission_revision, language, filters]
    encoded = json.dumps(payload, sort_keys=True, separators=(',', ':'),
                         ensure_ascii=False, allow_nan=False).encode('utf-8')
    return 'report:v1:' + hashlib.sha256(encoded).hexdigest()

left = report_cache_key(1, 3, 'en', {'status': 'open', 'year': 2026})
right = report_cache_key(1, 3, 'en', {'year': 2026, 'status': 'open'})
assert left == right
assert left != report_cache_key(2, 3, 'en', {'status': 'open', 'year': 2026})
# Include a user/visibility scope too if permission_revision is not enough.
# Hashing structures the key; it does not authorize a request.
import hashlib
import json

def report_cache_key(tenant_id, permission_revision, language, filters):
    # Caller supplies a validated, JSON-serializable filter mapping.
    payload = [tenant_id, permission_revision, language, filters]
    encoded = json.dumps(payload, sort_keys=True, separators=(',', ':'),
                         ensure_ascii=False, allow_nan=False).encode('utf-8')
    return 'report:v1:' + hashlib.sha256(encoded).hexdigest()

left = report_cache_key(1, 3, 'en', {'status': 'open', 'year': 2026})
right = report_cache_key(1, 3, 'en', {'year': 2026, 'status': 'open'})
assert left == right
assert left != report_cache_key(2, 3, 'en', {'status': 'open', 'year': 2026})
# Include a user/visibility scope too if permission_revision is not enough.
# Hashing structures the key; it does not authorize a request.
import hashlib
import json

def report_cache_key(tenant_id, permission_revision, language, filters):
    # Caller supplies a validated, JSON-serializable filter mapping.
    payload = [tenant_id, permission_revision, language, filters]
    encoded = json.dumps(payload, sort_keys=True, separators=(',', ':'),
                         ensure_ascii=False, allow_nan=False).encode('utf-8')
    return 'report:v1:' + hashlib.sha256(encoded).hexdigest()

left = report_cache_key(1, 3, 'en', {'status': 'open', 'year': 2026})
right = report_cache_key(1, 3, 'en', {'year': 2026, 'status': 'open'})
assert left == right
assert left != report_cache_key(2, 3, 'en', {'status': 'open', 'year': 2026})
# Include a user/visibility scope too if permission_revision is not enough.
# Hashing structures the key; it does not authorize a request.

68. How does Vary affect HTTP caching?

Vary tells caches which request headers influence the response representation. It helps prevent a cache from treating responses as interchangeable when, for example, language or another supported header changes the content.

Set it according to the actual representation and combine it with appropriate cache-control policy. Vary is not authorization and does not make a private response safe for shared caching by itself. Test the entire caching path, including reverse proxies and CDNs, because a correct application header is only one part of the deployed behavior.

69. How should an upload be validated and stored?

Validate size, permitted content and the intended operation, then store the file through the configured storage abstraction with an access policy suited to its sensitivity. Treat the supplied name and content type as untrusted metadata.

For a résumé upload, a generated storage key and controlled download path may be more appropriate than a public URL under the application origin. Consider scanning and processing limits where required. A successful database save does not atomically commit an object-storage write, so define cleanup and reconciliation for partial failures.

70. What is the purpose of collectstatic?

collectstatic gathers static assets from configured sources into the deployment's static storage destination. It supports a production asset-serving workflow rather than relying on the development server to locate files dynamically.

Use the selected storage backend and manifest behavior consistently with the deployed templates. A missing manifest entry can break a page even when the source file exists in the repository. User uploads do not belong in this collection step, and collecting files is separate from ensuring the web server or CDN can serve them correctly.

71. Why do data migrations use historical models?

Migration code must operate against the model state at that point in the migration graph. Obtaining models through the migration apps registry avoids importing today's model definition into a migration that may run against an older schema.

A fresh installation can replay migrations years after they were written, so current imports can fail even if the migration worked on its author's database. Keep required historical behavior self-contained or preserved appropriately. Test migration paths on realistic starting states rather than only checking the latest model tests.

72. How should a data migration's reverse operation be designed?

A reverse operation should honestly restore the intended previous state where that is possible. Some transformations lose information and cannot be safely reversed merely by writing a function with the opposite-looking assignment.

For a normalization that merges distinct old values, document irreversibility or preserve enough information under a deliberate migration strategy. A no-op reverse is not a true rollback of changed data. Deployment recovery may require backups, forward repair or a staged design, so distinguish schema reversal from business-data restoration.

73. How should tests check database-query efficiency?

Assert a meaningful query budget around the complete operation and use fixtures that reveal repeated relationship access. A one-row fixture can hide an N+1 pattern that becomes obvious with several parent objects.

Query-count helpers are useful, but count alone does not measure row volume, query complexity or latency. Pair them with plan inspection and representative performance evidence for important paths. Avoid brittle assertions that merely freeze incidental implementation details without protecting a real performance requirement.

74. How does RequestFactory differ from the test client?

RequestFactory creates request objects for calling views more directly, while the test client exercises more of the configured request-handling path. A factory-created request does not automatically acquire every middleware-provided attribute.

If a view expects a user or session, provide the needed state explicitly or use a test boundary that includes the relevant middleware. Direct view tests can isolate behavior efficiently, but they do not prove routing and middleware composition. Choose the tool based on what the assertion is intended to establish.

from django.http import JsonResponse
from django.test import RequestFactory, SimpleTestCase

def ping(request):
    return JsonResponse({'ok': True})

class PingTests(SimpleTestCase):
    def test_response_contract(self):
        response = ping(RequestFactory().get('/ping/'))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/json')
        self.assertJSONEqual(response.content, {'ok': True})

# Run in a configured Django test project.
# This does not exercise URL resolution or middleware.
from django.http import JsonResponse
from django.test import RequestFactory, SimpleTestCase

def ping(request):
    return JsonResponse({'ok': True})

class PingTests(SimpleTestCase):
    def test_response_contract(self):
        response = ping(RequestFactory().get('/ping/'))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/json')
        self.assertJSONEqual(response.content, {'ok': True})

# Run in a configured Django test project.
# This does not exercise URL resolution or middleware.
from django.http import JsonResponse
from django.test import RequestFactory, SimpleTestCase

def ping(request):
    return JsonResponse({'ok': True})

class PingTests(SimpleTestCase):
    def test_response_contract(self):
        response = ping(RequestFactory().get('/ping/'))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/json')
        self.assertJSONEqual(response.content, {'ok': True})

# Run in a configured Django test project.
# This does not exercise URL resolution or middleware.

75. Why can a default test client miss CSRF failures?

The ordinary test client relaxes CSRF checking by default to simplify many application tests. A successful POST through it therefore does not prove that the production CSRF flow is configured correctly.

Use a client configured to enforce CSRF checks for the tests that exercise that protection, and obtain and submit tokens through a realistic flow. Keep those tests distinct from authorization tests so a CSRF rejection does not mask an ownership bug. Browser-level tests may still be needed for origin, cookie and embedding behavior.

from django.test import Client

csrf_client = Client(enforce_csrf_checks=True)
# In a configured project, GET the form route, obtain its CSRF token,
# then POST with and without the token and assert the intended outcomes.
# Creating this client alone is not a completed CSRF integration test.
from django.test import Client

csrf_client = Client(enforce_csrf_checks=True)
# In a configured project, GET the form route, obtain its CSRF token,
# then POST with and without the token and assert the intended outcomes.
# Creating this client alone is not a completed CSRF integration test.
from django.test import Client

csrf_client = Client(enforce_csrf_checks=True)
# In a configured project, GET the form route, obtain its CSRF token,
# then POST with and without the token and assert the intended outcomes.
# Creating this client alone is not a completed CSRF integration test.

76. How should settings changes be isolated in tests?

Use Django's supported settings-override tools for a bounded test scope and ensure code reads settings at an appropriate time. A value copied into a module-level constant during import may not respond to a later override as expected.

A test of an upload limit should restore the original configuration afterward and avoid leaking state into unrelated tests. Also reset or recreate components that legitimately cache configuration where necessary. Changing a setting does not automatically reconfigure every external service or already-created connection.

77. How should signals be registered reliably?

Register receivers through an appropriate app initialization path and avoid duplicate registration when modules are imported or setup runs more than once. Use the supported receiver and dispatch-identification mechanisms where needed.

Keep registration separate from running database work during startup. Tests and management commands also initialize apps, so import-time queries can fail before migrations or create unwanted side effects. A receiver should remain small and have a clear failure and transaction policy rather than becoming an invisible replacement for the main workflow.

78. What does Django's Tasks framework provide and leave to infrastructure?

The Tasks framework provides an interface for defining and enqueueing background work, but actual execution requires an appropriate backend and worker infrastructure. The built-in development/testing backends should not be mistaken for a production worker service.

An email task needs a configured execution system, monitoring and a policy for retries and repeated delivery. Enqueueing after database commit avoids one visibility race but does not by itself guarantee durable delivery. State the supported Django version because this framework is a newer facility and older projects may use different task systems.

79. How should a management command process a large dataset?

Use a bounded iteration and transaction strategy, clear progress reporting and a restart policy. Loading every row into memory or holding one long transaction can make an otherwise simple command operationally risky.

Process stable batches and record enough identity to resume without duplicating completed effects. Decide whether concurrent changes are included or excluded, and test failure between batches. A progress count alone is not a reconciliation record if records can be inserted, removed or reordered during the run.

80. How should a reusable Django app avoid project-specific coupling?

Keep settings, model references, URL names and extension points explicit, and avoid importing one project's concrete configuration or user model throughout the app. Document the versions and integration steps the app requires.

A reusable notification app can expose a small API and configurable templates while letting the host project decide its business events. Do not make every detail configurable merely to claim reuse; excessive options create untested combinations. Test at least one minimal host project so packaging and initialization assumptions are exercised.

Django Interview Questions and Answers for Experienced

These answers require reasoning about guarantees across requests, processes and external systems.

81. How would you introduce a required field without breaking a rolling deployment?

Use a staged schema and application transition that remains compatible with old and new code while both may run. Add the field in a compatible form, deploy code that can populate and tolerate the transitional state, backfill existing rows, then enforce the final requirement when the data and deployed versions support it.

Check the actual database's locking and default-handling behavior before applying the migration. A generated migration that succeeds on a small development database can block a large production table. Define rollback and forward-repair options at each stage rather than assuming one deployment switch changes every process simultaneously.

82. How would you investigate migration drift?

Compare the migration graph, recorded applied migrations and actual schema before changing anything. Drift can arise from manual DDL, missing files, different branches or a previously faked migration, and each cause needs a different repair.

Do not use --fake simply to remove an error message without proving that the schema matches the state being recorded. Reproduce the relevant path on a representative copy and preserve evidence of the discrepancy. A safe repair aligns both schema and migration history while accounting for existing data and deployed code.

83. How should concurrent migration branches be reconciled?

Inspect the operations and dependencies from both branches and determine whether they can be combined without conflicting state or data assumptions. A merge migration can join the graph, but it does not resolve incompatible field changes by magic.

Test from the shared predecessor and from any already deployed branch state that must remain supported. Rename detection and data operations deserve particular care. Keep the final graph reproducible in a fresh database and document any deliberate data reconciliation rather than editing applied history casually.

84. How would you enforce a reservation invariant under concurrency?

Express as much of the invariant as possible in database constraints and use a transaction strategy appropriate to the remaining decision. A Python check followed by an insert is vulnerable when two requests both observe availability before either commits.

For unique slots, a unique constraint may be sufficient; overlapping time ranges may need backend-specific constraints or a carefully designed locking model. Test competing transactions on the real database engine and map conflicts to a useful user outcome. Do not promise that atomic alone serializes every possible conflicting read.

85. How should a Django endpoint make repeated write requests idempotent?

Define a stable operation key and persist the operation's result or state under a database uniqueness rule. Repeated requests with the same key should reconcile the same logical operation, including rejecting incompatible reuse of that key with different input.

Store the key and business transition within the intended transaction boundary. A cache entry alone may expire or be lost, and a client-side disabled button cannot prevent network retries. Consider failures after commit but before the response reaches the client, because that is where a naive retry often creates a duplicate.

86. What does durable=True add to an atomic block?

A durable atomic block requires an outermost transaction boundary in ordinary application use, so successful exit commits rather than merely releasing an inner savepoint. Nesting it inside another atomic block raises RuntimeError instead of silently postponing that boundary.

Use this when a function's contract truly requires its own commit boundary, and consider callers such as ATOMIC_REQUESTS that may already wrap it. The option does not make external messages transactional or override the database's physical durability configuration. Django TestCase has special durability-check behavior, so verify the production nesting contract with an appropriate transaction test rather than inferring it from a fast isolated test.

87. How should database deadlocks be handled?

Keep transactions short, acquire locks in a consistent order where possible and use indexes and query plans that reduce unnecessary locked work. When the database aborts a transaction, retry only a safe, bounded unit of work with an understood side-effect policy.

Do not retry just the last SQL statement inside a transaction whose state has already been rolled back or broken. Capture the conflicting operations and database diagnostics to fix recurring causes. External calls performed before the abort may still have happened, so a retry policy must account for them explicitly.

88. How should a multi-tenant query boundary be designed?

Tenant scope should be enforced consistently in data access, relationship selection and operations, with tests that attempt cross-tenant access through every supported entry point. A tenant filter in one list view is not a complete boundary.

Consider managers or service APIs that make the scope explicit, while reviewing escape paths such as raw SQL, admin actions and background tasks. Database-level isolation can add protection where appropriate but introduces its own connection and policy requirements. Avoid hidden global request state that can leak across asynchronous or reused execution contexts.

89. What problems arise when reading from replicas after a write?

Replication can lag, so a subsequent read from a replica may not observe the just-committed write. Routing every read away from the primary can therefore make a successful operation appear missing or stale.

Define which workflows require read-your-writes behavior and route or synchronize them accordingly. Django database routers do not automatically solve replication lag, transaction boundaries or failover consistency. Test the user-visible sequence under delayed replication and document the acceptable staleness of reporting paths separately from critical confirmation paths.

90. How would you debug an N+1 problem that survives prefetching?

Inspect the exact relationship access and generated queries rather than assuming the presence of prefetch_related proves the cache is used. A later filtered related lookup, a property or a serializer can issue queries different from the prefetched lookup.

Use representative multiple-parent fixtures and trace the full response rendering. A tailored Prefetch with an explicit result attribute can make the intended collection clearer. Balance the query reduction against memory and row volume, and avoid prefetching a huge graph simply to force the count down.

91. How should a slow ORM query be analyzed?

Inspect the generated SQL, parameters, execution plan and realistic data distribution. Determine whether the cost comes from joins, scans, sorting, row estimates, transferred data or repeated execution before changing the Python expression.

An index can help one filter and still make writes more expensive or fail to support the actual ordering. Measure the complete request and compare equivalent semantics after each change. Replacing ORM code with raw SQL is justified by a demonstrated need, not by assuming that hand-written SQL is always faster.

92. When is keyset pagination preferable to high offsets?

Keyset pagination advances from a stable ordered key rather than asking the database to skip an increasingly large number of earlier rows. It can improve performance and consistency for sequential browsing of large changing datasets.

Use a deterministic ordering with a unique tie-breaker and encode the cursor's relevant values safely. It does not naturally support arbitrary page-number jumps, and changes to sort fields can still affect navigation. Define the consistency contract and authorization scope so a cursor cannot be reused to escape into another tenant's results.

93. How should cache invalidation coordinate with transactions?

Avoid publishing a new cache value before the database transaction that justifies it commits. Otherwise, a rollback can leave cached data describing a state that never became authoritative.

Invalidate or update after commit where that is sufficient, and consider versioned keys or a more durable event path when missed invalidations are unacceptable. Concurrent readers can still refill a cache with stale data around the transition, so analyze the actual interleaving. A short TTL limits staleness but does not establish correctness for decisions that require current data.

94. How would you control a cache stampede?

Limit duplicate recomputation when a popular entry expires by using an appropriate coordination or stale-serving strategy. The choice depends on whether callers may temporarily receive old data and whether the backend offers the required atomic operations.

A local in-process lock coordinates only that process, not every worker in a deployment. Bound lock ownership and recovery so a failed recomputation does not block the key forever. Measure downstream load during expiry bursts rather than only the steady-state hit rate, and keep authorization-sensitive data separated while coalescing work.

95. How should an async view react to client disconnection?

Handle cancellation through the supported request lifecycle, release owned resources and propagate cancellation appropriately after cleanup. A disconnected client does not imply that every downstream write was canceled or rolled back.

For long-running work, decide whether it belongs in the request at all or should be represented as a durable job with a status endpoint. Do not swallow cancellation as an ordinary success and continue unlimited work. Test the server and middleware stack actually deployed, since disconnect and streaming behavior depend on that integration.

96. What transaction risks accompany a streaming response?

Streaming content is produced after the view returns, so code generating it can run outside a request-level transaction that wrapped the view. A failure after headers or partial content are sent cannot be handled like an ordinary pre-response error.

Avoid making important database writes while streaming merely because ATOMIC_REQUESTS is enabled. Prepare the required consistent data or use an explicitly designed streaming contract. Bound resource lifetime and handle client cancellation, and distinguish a partially delivered export from a completed, auditable business operation.

97. How should persistent database connections be assessed under async serving?

Django 6.1 recommends disabling persistent database connections configured through CONN_MAX_AGE in async mode and using an appropriate backend pool where available. Settings that are sensible for a synchronous worker arrangement should not be copied into an async deployment without checking their support and ownership implications.

Use the supported pooling approach where appropriate and measure total connections across processes and tasks. A pool limit is part of capacity planning, not only a latency optimization. Keep transactions and connection-sensitive work within supported boundaries, and test exhaustion and recovery rather than just a successful request.

98. How should request-context data reach background work?

Pass a small explicit description of the operation, including stable identifiers and the relevant authorization or audit context, rather than serializing the live request object. A task may run after the session, process or referenced data has changed.

Recheck the permissions and state required by the operation at execution time according to its business contract. Decide whether the task acts under a captured approved command or the user's current authority. Including a user ID is useful context but is not itself proof that the later action remains authorized.

99. How should secret-key rotation be planned?

Identify every feature that relies on signed data and use the framework's supported rotation and fallback facilities where applicable. Keep old keys only for the compatibility window actually required and protect them as carefully as the new key.

Test sessions, signed links and other affected tokens under the real backend and timeout policies. Removing a fallback can invalidate outstanding data, which may be intentional but should be understood. Never log the keys during diagnosis or assume that changing one setting automatically rotates unrelated database, storage or external-service credentials.

100. How should proxy headers be trusted in a Django deployment?

Trust forwarded host or scheme information only when the application's proxy chain is controlled and strips or replaces untrusted client-supplied values. The correct settings depend on where TLS terminates and which component establishes the header.

A misconfigured secure-proxy header can make Django believe an insecure request is secure or generate incorrect redirects. Test direct and proxied paths, including attempts to supply the header from outside the trusted boundary. Do not fix a redirect loop by weakening security settings without understanding which hop reports the original scheme.

101. How would you prevent a personalized response from entering a shared cache?

Classify the response's sensitivity and configure cache-control, variation and cache placement accordingly. A shared cache must not reuse a response across users merely because the URL matches.

Test with two distinct accounts and an anonymous request through the real proxy or CDN path, not just Django's local cache. Review error pages and redirects as well as successful pages, since they can contain user-specific information too. A user identifier in an application cache key does not automatically configure an independent HTTP cache.

102. How should signing differ from encryption in application design?

Signing detects unauthorized modification of data under the relevant key; it does not hide the data from someone who can read it. A signed cookie or URL should therefore not contain information that must remain confidential solely because its signature is valid.

Use a narrow payload, appropriate expiration and purpose separation for signed values. When confidentiality is required, choose a suitable storage or encryption design with explicit key ownership. Also validate the decoded data's meaning: a valid signature does not make an expired or context-inappropriate action acceptable.

103. How should uploaded content be served safely?

Separate untrusted uploads from executable application content and apply an access policy, content handling and origin strategy suitable to the file type and sensitivity. Upload validation and safe delivery are complementary controls.

A document preview can require authorization and a restrictive content disposition rather than allowing arbitrary active content on the main application origin. Test browser interpretation and storage metadata, not just the filename accepted by the form. Cleanup and retention must also account for database records that fail or are removed while the object remains stored.

104. How should admin bulk actions preserve business invariants?

Treat an admin action as a privileged application operation with explicit selection, permission, transaction and partial-failure behavior. It should not bypass important rules merely because the operator is staff.

For bulk approval, verify each object's eligible state and the operator's authority, then report exactly which records changed. QuerySet.update may bypass instance hooks, while looping over save calls has different cost and failure behavior. Choose deliberately and record an audit outcome that supports reconciliation after an interrupted action.

105. What should a custom authentication backend guarantee?

It should implement the expected authentication contract, handle missing or invalid credentials consistently and integrate with the application's user and permission model. External identity verification needs deadlines and a clear failure policy.

Do not create a local privileged user merely because an upstream response contains a familiar email address; bind identity through the trusted provider's verified identifier and contract. Test disabled accounts, backend ordering and outages. Authentication backend behavior and permission aggregation can interact, so review the complete configured set.

106. How should a reusable app reference the configured user model in migrations?

Use the supported swappable dependency and model-reference mechanisms so the migration graph respects the project's configured user model. Importing one concrete user class into migration code can break projects with a different configuration.

Test installation in a minimal project with a custom user model, including a fresh database. Runtime get_user_model usage and historical migration model lookup serve different purposes and should not be substituted blindly. Reusability requires the migration history to work, not only the latest models importing successfully.

107. How should a large historical backfill be made restartable?

Use stable batches, an explicit progress or eligibility condition and operations that can be safely repeated. Separate the long-running data work from a schema transition when that makes deployment and recovery more manageable.

A timestamp or primary-key checkpoint must match the ordering and mutation assumptions of the dataset. Concurrent updates may require version checks or a reconciliation pass. Track failures by identity and validate totals or invariants after completion; reaching the last batch is not sufficient evidence that every intended row was transformed correctly.

def batches_by_count(items, size):
    if isinstance(size, bool) or not isinstance(size, int) or size <= 0:
        raise ValueError('size must be a positive integer')
    batch = []
    for item in items:
        batch.append(item)
        if len(batch) == size:
            yield batch
            batch = []
    if batch:
        yield batch

assert list(batches_by_count(range(5), 2)) == [[0, 1], [2, 3], [4]]
assert list(batches_by_count([], 2)) == []
# Bounded grouping only. The caller still owns stable query ordering,
# checkpoint persistence, transactions and restart reconciliation.
def batches_by_count(items, size):
    if isinstance(size, bool) or not isinstance(size, int) or size <= 0:
        raise ValueError('size must be a positive integer')
    batch = []
    for item in items:
        batch.append(item)
        if len(batch) == size:
            yield batch
            batch = []
    if batch:
        yield batch

assert list(batches_by_count(range(5), 2)) == [[0, 1], [2, 3], [4]]
assert list(batches_by_count([], 2)) == []
# Bounded grouping only. The caller still owns stable query ordering,
# checkpoint persistence, transactions and restart reconciliation.
def batches_by_count(items, size):
    if isinstance(size, bool) or not isinstance(size, int) or size <= 0:
        raise ValueError('size must be a positive integer')
    batch = []
    for item in items:
        batch.append(item)
        if len(batch) == size:
            yield batch
            batch = []
    if batch:
        yield batch

assert list(batches_by_count(range(5), 2)) == [[0, 1], [2, 3], [4]]
assert list(batches_by_count([], 2)) == []
# Bounded grouping only. The caller still owns stable query ordering,
# checkpoint persistence, transactions and restart reconciliation.

108. How would you test row-locking behavior correctly?

Use the production database engine or a representative equivalent with separate connections and controlled coordination points. Assert the intended blocked, skipped or conflicting outcome rather than relying on arbitrary sleeps.

Choose a test class and transaction setup that expose actual commit and lock boundaries. TestCase's surrounding transaction can make select_for_update appear valid in situations that would fail under normal autocommit. Include timeout and cleanup paths so a failed assertion does not leave the test hanging indefinitely, and state what the test does not prove about all possible interleavings.

Test choice

Useful evidence

Limit

Single-connection unit test

Local logic and validation

No competing lock owner

TestCase

Fast application database tests

Outer transaction can alter behavior

Separate connections on target engine

Actual lock/conflict scenario

Still a finite set of interleavings

109. How can on_commit callbacks be tested inside TestCase?

TestCase normally rolls back its enclosing transaction, so callbacks waiting for a real commit will not run in the ordinary way. captureOnCommitCallbacks can capture registered callbacks for a chosen database alias and optionally execute them to emulate the commit-triggered behavior.

Assert both that the intended callback was registered and that its controlled effect is correct, using execute=True where appropriate. This does not perform a real database commit or prove durable external delivery. Use TransactionTestCase or a suitable integration test when actual commit visibility or interaction with another connection is the behavior under examination.

110. How should test isolation cover caches and external effects?

Database rollback does not reset every cache, file, message queue or external service touched by a test. Provide controlled substitutes or isolated resources and clean up the state owned by the test.

A notification test can capture an email or enqueue operation without sending to real recipients, then separately test the integration in an approved environment. Use unique namespaces where shared test infrastructure is unavoidable. A passing suite that depends on execution order or leftover cache entries is not reliable evidence of application correctness.

111. How would you upgrade Django with manageable risk?

Review release notes and deprecations for each supported transition, update dependencies and exercise representative workflows in the target configuration. Resolve warnings and incompatible behavior deliberately rather than suppressing them until the server starts.

Test migrations, authentication, templates, async paths and deployment settings as well as unit-level business logic. Keep the upgrade bounded enough to diagnose regressions and define a recovery plan compatible with any schema changes. A successful package installation does not establish that third-party apps or production operations support the new release.

112. How should third-party Django packages be evaluated?

Check compatibility, maintenance, security history, migration behavior, public APIs and the operational dependency they introduce. Evaluate the actual required feature rather than choosing a package solely because it is popular.

A package that replaces authentication or storage becomes part of a sensitive boundary and deserves realistic failure tests. Review how data can be exported or migrated away and who owns updates. Pinning a version supports reproducibility, but a frozen unsupported dependency is not a long-term maintenance strategy.

113. How should settings be validated across environments?

Make required configuration explicit, fail clearly on invalid critical values and run checks against the settings used by the actual deployment. Avoid a silent fallback that makes production behave like a permissive development environment.

Validate relationships among values, such as trusted proxy settings and HTTPS handling, rather than only checking that strings are nonempty. Keep secrets out of diagnostic output. A configuration test can establish parsing and invariants, but connectivity, permissions and service behavior still require environment-specific verification.

114. How should error monitoring preserve useful context without leaking data?

Record the route or operation, safe identifiers, failure category and correlation information needed for diagnosis, while redacting credentials and sensitive payloads. Review automatic traceback and request-context capture as well as explicit logging calls.

A failed form submission may contain passwords or personal documents, so dumping request.POST is not an acceptable default. Test redaction on the actual failure path and control retention and access. Monitoring should distinguish an application error from a client validation failure so routine bad input does not bury actionable incidents.

115. How should database and file-storage consistency be reconciled?

Recognize that an ordinary database transaction does not atomically commit an external object-storage operation. Design explicit states, compensating cleanup or a reconciliation process for the possible partial outcomes.

For an upload, a temporary object can be promoted or associated only after validation, while a periodic process identifies orphaned objects under a defined retention policy. Do not delete blindly based on one transient database observation. Track ownership and operation identity so retries and recovery preserve the user's intended file rather than producing duplicates or losing the only valid copy.

116. How should schema rollback differ from application rollback?

An application rollback restores an earlier code version, while a schema rollback changes database structure or data and may be destructive or incompatible with surviving processes. They must be planned together but are not the same action.

A backward-compatible additive schema can let old code run without reversing the migration, while a dropped column cannot be restored with its old contents merely by recreating its name. Define the supported version overlap and recovery evidence before release. Prefer a deliberate forward repair when reversing data would create greater risk.

117. How should a background task handle repeated delivery?

Assume the selected execution system may retry or redeliver according to its contract, and make the task's business effect idempotent or reconcilable. A task ID in a log is not enough unless it participates in the operation's state rules.

For a report-generation task, reuse or reconcile the intended output under a stable key and distinguish incomplete work from a completed result. For external writes, use the provider's supported idempotency mechanism where available. Acknowledgment timing and retry policy must be evaluated with the actual backend and worker infrastructure.

118. How would you diagnose a memory-heavy export endpoint?

Trace where query results, related objects, rendered output and encoded bytes are materialized. Several individually reasonable conversions can hold multiple copies of a large dataset at once.

Use bounded iteration or a background export workflow where appropriate, but verify database cursor and server behavior rather than assuming iterator means constant memory everywhere. Streaming changes error and transaction semantics, so it is not only a memory switch. Measure representative volumes and cancellation to ensure abandoned exports release resources.

119. How would you design a practical senior Django interview exercise?

Give the candidate a small workflow with a meaningful invariant, such as reserving the last available slot, and ask for the request, model, transaction and test design. Include a second concurrent request and a failure after database commit to reveal assumptions.

Strong answers identify which guarantees come from constraints, which require application coordination and what must be tested on the actual backend. Keep the exercise small enough to inspect rather than rewarding boilerplate volume. Follow up with a permission change or rolling-deployment constraint to assess whether the design remains coherent.

120. What evidence should support a production Django release?

The release should have evidence for its important user workflows, authorization boundaries, database changes, resource behavior and recovery paths in the intended environment. Tests and deployment checks contribute different parts of that evidence.

For a data-changing feature, include migration rehearsal, conflict behavior, monitoring and a recovery plan alongside successful request tests. State unresolved limitations and the responsible owner. A green unit suite and a successful server startup do not by themselves establish that the application can handle realistic traffic, partial failures or operational handover.

  1. Verify critical user and authorization paths.

  2. Rehearse schema/data transitions and recovery.

  3. Exercise representative load and partial failures.

  4. Confirm monitoring, ownership and unresolved limits.

Django Documentation and Further Reading

These official resources document the framework contracts and version-specific behavior discussed here. All ten Python examples received syntax and static review; three standalone helpers were executed locally. Django was unavailable in the local environment and its isolated installation returned no matching distribution, so the seven framework-dependent examples were not executed. No production database concurrency, migration, worker, proxy, storage service or browser integration test is claimed.

Team Sherlock.sh

Building fraud intelligence for live high-stake video interactions (financial discussions, hiring interviews, board meeting etc).

Catch candidate fraud before it costs you.

Sherlock AI helps you detect AI-assisted, proxy, and deepfake candidates, so every hiring decision is backed by evidence.

Ask AI about Sherlock.sh

Similar Posts