Fun with Learning Technology
LearnCoursesQuestionsTracksToolsNewsExplorePractice
Fun with Learning Technology

A new problem, explained clearly, every day.

Subscribe
Learn
  • Lessons
  • Topics
  • News
  • Tools
  • Courses
  • Career tracks
  • Everything
Site
  • About
  • Contact
  • Support
  • Privacy
  • Terms
Get the daily one

One email per new problem. No spam.

Request a tutorial

Requests shape what gets made next.

© 2026 Fun with Learning TechnologyRSS
Home›Django›Quiz

Django quiz

Ten questions at a time, drawn from 150. Every answer is explained. Nothing is saved and no account is needed.

Question 1 of 10Score 0

If you need to change how a specific database table structure is represented in your application, which component of the MTV architecture should you modify?

Practice quiz for Django. Scores are not saved.

Study first?

Every question comes from a lesson in the Django course.

Read the course →

Interview prep

Written questions with full answers.

Django interview questions →

All Django quiz questions and answers

  1. If you need to change how a specific database table structure is represented in your application, which component of the MTV architecture should you modify?

    • The Template
    • The View
    • The Model
    • The URL configuration

    Answer: The Model. The Model handles the data structure and schema. Changing the View or Template only affects how data is processed or displayed, not how it is defined. The URL config only maps requests.

    From lesson: Django MTV Architecture

  2. A developer wants to fetch a list of user profiles from the database and pass them to an HTML page. Where should the database query code reside?

    • Inside the Template as a raw SQL tag
    • Inside the View function to prepare the context
    • Inside the URL configuration file
    • Inside the Middleware only

    Answer: Inside the View function to prepare the context. The View is responsible for retrieving data and passing it to the Template. Templates should never execute database queries, and URL configs are for routing, not logic.

    From lesson: Django MTV Architecture

  3. What is the primary responsibility of the Template in the Django MTV pattern?

    • Defining the business logic and database constraints
    • Routing user requests to the appropriate functions
    • Defining the presentation layer and how data is displayed to the user
    • Handling the authentication tokens for secure sessions

    Answer: Defining the presentation layer and how data is displayed to the user. Templates are strictly for presentation. Business logic, routing, and authentication occur in Models, Views, and Middleware, respectively.

    From lesson: Django MTV Architecture

  4. Why is it considered bad practice to put complex calculation logic inside a Django Template?

    • Templates are strictly for rendering, and logic makes them hard to maintain and test
    • Django templates automatically prevent all calculations for security
    • It would make the View redundant
    • The Model would stop receiving data from the database

    Answer: Templates are strictly for rendering, and logic makes them hard to maintain and test. Templates should be simple. Logic in templates is harder to debug and violates the separation of concerns. The View is specifically designed to handle logic before rendering.

    From lesson: Django MTV Architecture

  5. In Django's MTV architecture, which component acts as the bridge that retrieves data from the Model and serves it to the Template?

    • The Middleware
    • The View
    • The Settings file
    • The URL Router

    Answer: The View. The View is the intermediary. It processes the request, talks to the Model to get data, and passes that data into a Template for the final response.

    From lesson: Django MTV Architecture

  6. What is the primary architectural purpose of splitting a Django project into multiple apps?

    • To allow different developers to work on different files simultaneously.
    • To logically encapsulate specific features, making them reusable across different projects.
    • To increase the speed at which the Django development server restarts.
    • To force the database to use separate schemas for each application.

    Answer: To logically encapsulate specific features, making them reusable across different projects.. The correct answer is encapsulating features for reusability. The other options are incorrect because multi-app structures are about code organization and modularity, not about performance tuning, database schemas, or file-locking conflicts.

    From lesson: Project and App Structure

  7. Why is it mandatory to include a newly created app in the 'INSTALLED_APPS' list within 'settings.py'?

    • To inform the Django template engine about the existence of the app's templates.
    • To ensure the development server recognizes the folder as a valid directory.
    • To allow Django to detect the app's models, migrations, and template tags.
    • To force the project to build a separate database table for the app's configuration.

    Answer: To allow Django to detect the app's models, migrations, and template tags.. The correct answer is to allow Django to detect models and migrations. Without this, Django does not load the app's configuration, so the other options are wrong because they describe functionality that does not depend on the app registry or is simply false.

    From lesson: Project and App Structure

  8. Which of the following describes the correct role of the project-level 'urls.py' versus an app-level 'urls.py'?

    • The project 'urls.py' handles all business logic, while the app 'urls.py' only handles static files.
    • The project 'urls.py' acts as a central router that includes app-specific URL patterns.
    • The project 'urls.py' must define every URL path in the entire project.
    • The app 'urls.py' is used to override the project's global security settings.

    Answer: The project 'urls.py' acts as a central router that includes app-specific URL patterns.. The project 'urls.py' acts as a central router. The other options are wrong because they misrepresent the delegation of concerns: apps should manage their own paths, and the project root should never hold the entirety of the project's routing.

    From lesson: Project and App Structure

  9. If you are following the Django 'fat-model, thin-view' principle, where should you ideally perform data validation that involves multiple fields of a model?

    • Inside the view function before saving the model instance.
    • Inside the template using conditional tags.
    • Inside the model's clean method or a custom save method.
    • Inside the project's 'settings.py' file.

    Answer: Inside the model's clean method or a custom save method.. Validation belongs in the model because it ensures data integrity regardless of where the data is updated. Views, templates, and settings are inappropriate for model-level business logic, making those options incorrect.

    From lesson: Project and App Structure

  10. What is the consequence of placing a 'templates' directory at the root of your project instead of inside an app folder?

    • Django will automatically search the root for templates before app folders.
    • Django will crash immediately because it expects templates to be in apps.
    • The template will not be found unless specifically configured in 'TEMPLATES' settings.
    • It increases the loading speed of the templates significantly.

    Answer: The template will not be found unless specifically configured in 'TEMPLATES' settings.. Django defaults to looking for templates inside app directories; a root folder must be explicitly added to the 'DIRS' list in 'TEMPLATES' to be found. The other options are wrong because they assume automatic behavior or claim impossible results like faster performance.

    From lesson: Project and App Structure

  11. If you move your project to a new machine, why should you use BASE_DIR instead of a static file path?

    • It prevents unauthorized access to the filesystem.
    • It ensures path resolution is relative to the project root regardless of the operating system's absolute directory structure.
    • It automatically optimizes the file loading speed for static assets.
    • It forces Django to store all media files inside the virtual environment.

    Answer: It ensures path resolution is relative to the project root regardless of the operating system's absolute directory structure.. BASE_DIR allows for relative path construction, ensuring compatibility across different environments. The other options are incorrect because BASE_DIR does not handle security, performance, or file storage locations.

    From lesson: Settings — BASE_DIR, Installed Apps, Middleware

  12. What is the primary reason for the specific order of classes in the MIDDLEWARE setting?

    • The order determines the priority of database connections.
    • The order controls the order in which Python modules are imported.
    • Middleware behaves like a layered stack; request-phase processing goes top-to-bottom, while response-phase processing goes bottom-to-top.
    • The order is enforced by the operating system to prevent security vulnerabilities.

    Answer: Middleware behaves like a layered stack; request-phase processing goes top-to-bottom, while response-phase processing goes bottom-to-top.. Django middleware functions as a layered system; request/response processing order is critical for dependencies like sessions and authentication. Other options are incorrect because order does not affect database connections, imports, or OS security.

    From lesson: Settings — BASE_DIR, Installed Apps, Middleware

  13. When you create a new application using 'python manage.py startapp', why must you update INSTALLED_APPS?

    • Django needs to compile the app's code into the main project binary.
    • It informs Django to scan the app for models, template tags, and management commands.
    • It registers the app's database schema in the global project settings.
    • It is required to link the app's static files to the server's public folder.

    Answer: It informs Django to scan the app for models, template tags, and management commands.. Adding an app to INSTALLED_APPS is the mechanism for discovery. The other options are false because Django doesn't compile to binaries, doesn't register schemas directly in settings, and doesn't handle static file linking via that list.

    From lesson: Settings — BASE_DIR, Installed Apps, Middleware

  14. What happens if a required Middleware component is missing from the MIDDLEWARE setting?

    • The project will fail to start up completely.
    • Django will automatically substitute it with a default fallback.
    • Key features, such as CSRF protection or user authentication, will likely become non-functional or throw errors.
    • The web server will automatically bypass that specific functionality.

    Answer: Key features, such as CSRF protection or user authentication, will likely become non-functional or throw errors.. Removing essential middleware usually breaks dependent features, not the boot process itself. Django does not provide automatic fallbacks, and the server cannot 'bypass' functionality in a way that preserves app integrity.

    From lesson: Settings — BASE_DIR, Installed Apps, Middleware

  15. Which of the following best describes the role of the INSTALLED_APPS setting?

    • It defines which apps are currently running in the development server's memory.
    • It provides a list of all packages installed in the virtual environment.
    • It is a configuration list that defines which Django apps are active for the current project context.
    • It dictates the order in which templates are rendered.

    Answer: It is a configuration list that defines which Django apps are active for the current project context.. INSTALLED_APPS is the active list for the project. It is distinct from the virtual environment's packages and does not control memory processes or template rendering priority.

    From lesson: Settings — BASE_DIR, Installed Apps, Middleware

  16. What is the purpose of registering a model in the Django Admin?

    • To define the database schema for the model
    • To make the model manageable via the web-based admin interface
    • To automatically generate frontend templates for the model
    • To enable API serialization for the model

    Answer: To make the model manageable via the web-based admin interface. Registering a model allows the admin framework to build a UI for it. Option 0 is handled by migrations, option 2 is unrelated to admin, and option 3 refers to Django Rest Framework.

    From lesson: Django Admin Panel

  17. If you want to modify how a model's list view appears in the admin, which attribute should you configure in ModelAdmin?

    • list_display
    • fields
    • readonly_fields
    • search_fields

    Answer: list_display. list_display controls the columns shown on the list page. 'fields' controls form layout, 'readonly_fields' makes data non-editable, and 'search_fields' enables the search input.

    From lesson: Django Admin Panel

  18. Why would a developer use 'readonly_fields' in a ModelAdmin class?

    • To prevent the admin from querying the database
    • To hide the model from the admin sidebar
    • To display field data that users should be able to see but not change
    • To automatically encrypt field data in the database

    Answer: To display field data that users should be able to see but not change. readonly_fields allows displaying fields like timestamps or calculated data that shouldn't be edited. It does not hide models or handle encryption.

    From lesson: Django Admin Panel

  19. What is the primary function of the 'list_filter' attribute in a ModelAdmin class?

    • To restrict which rows appear based on user permissions
    • To create a sidebar that allows filtering records by specific fields
    • To hide specific columns from the list view
    • To validate form input before saving to the database

    Answer: To create a sidebar that allows filtering records by specific fields. list_filter adds a UI sidebar for filtering data. Permissions are handled by 'has_view_permission', column visibility is 'list_display', and validation is handled by 'clean' methods.

    From lesson: Django Admin Panel

  20. When should you override the 'save_model' method in ModelAdmin?

    • When you need to add custom logic immediately before or after saving an object via the admin
    • When you want to change the database table name for a model
    • When you want to add a new button to the admin header
    • When you want to prevent a user from deleting an object

    Answer: When you need to add custom logic immediately before or after saving an object via the admin. save_model is the hook for custom logic during the admin save process. Changing table names is a model Meta attribute, buttons require custom templates, and deletions are handled by 'delete_model'.

    From lesson: Django Admin Panel

  21. Which of the following describes the functional difference between path() and re_path() in Django?

    • path() supports named capturing groups, while re_path() only supports positional arguments.
    • path() uses simplified route syntax, whereas re_path() allows for full regular expression pattern matching.
    • path() is only for static files, while re_path() is for dynamic view routing.
    • re_path() is deprecated in newer Django versions and should never be used.

    Answer: path() uses simplified route syntax, whereas re_path() allows for full regular expression pattern matching.. Option 2 is correct because path() is designed for simpler, cleaner URL definitions, while re_path() provides the power of Python's re module. Option 1 is incorrect because both support named capturing. Option 3 is incorrect because both route to views. Option 4 is incorrect because re_path() remains a supported utility for complex routing.

    From lesson: URL Routing — path() and re_path()

  22. If your URL pattern is path('profile/<slug:name>/', views.profile), what happens if a user visits '/profile/john-doe_123/'?

    • It will raise a 404 error because the slug converter does not support underscores.
    • It will raise a 404 error because the slug converter does not support numbers.
    • It will match successfully and pass 'john-doe_123' as the name argument.
    • It will trigger a 500 server error due to invalid path syntax.

    Answer: It will match successfully and pass 'john-doe_123' as the name argument.. Option 3 is correct because the slug converter in Django matches characters including letters, numbers, hyphens, and underscores. Options 1 and 2 are incorrect because slugs explicitly allow these characters. Option 4 is incorrect as the syntax provided is standard for Django.

    From lesson: URL Routing — path() and re_path()

  23. Why is it recommended to order urlpatterns from most specific to least specific?

    • Django caches patterns and performs better when sorted by length.
    • The first pattern that matches the requested path is the one that is used.
    • It prevents the server from throwing a memory error during request parsing.
    • It allows Django to ignore trailing slashes automatically.

    Answer: The first pattern that matches the requested path is the one that is used.. Option 2 is correct because Django stops searching after the first match. Option 1 is incorrect as order doesn't impact caching. Option 3 is incorrect because order has no effect on memory. Option 4 is incorrect because URL order has nothing to do with slash management.

    From lesson: URL Routing — path() and re_path()

  24. When using re_path(r'^blog/(?P<year>[0-9]{4})/$', views.archive), how does Django pass the 'year' to the view?

    • As a keyword argument named 'year'.
    • As a positional argument in the order defined.
    • As part of the request.GET dictionary.
    • It does not pass the year, it must be accessed via request.path.

    Answer: As a keyword argument named 'year'.. Option 1 is correct because the ?P<name> syntax explicitly defines a named capture group which is passed to the view as a keyword argument. Option 2 is incorrect because the name syntax forces keyword usage. Options 3 and 4 are incorrect because URL parameters are passed as function arguments.

    From lesson: URL Routing — path() and re_path()

  25. If you want to create a URL pattern that captures a UUID, which is the most efficient and readable method?

    • Use re_path(r'^(?P<id>[a-f0-9-]{36})/$', view).
    • Use path('<uuid:id>/', view).
    • Use path('<str:id>/', view) and validate in the view.
    • Use re_path(r'^.+/$', view) and parse the string manually.

    Answer: Use path('<uuid:id>/', view).. Option 2 is correct because the built-in uuid converter is the idiomatic and most readable way to handle UUIDs. Option 1 is valid regex but less readable. Option 3 adds unnecessary logic to the view. Option 4 is highly inefficient and prone to errors.

    From lesson: URL Routing — path() and re_path()

  26. What is the primary requirement for a Python function to be considered a valid Django view?

    • It must be decorated with @login_required
    • It must accept a request object and return an HttpResponse object
    • It must be defined inside a views.py file
    • It must include a queryset attribute for database access

    Answer: It must accept a request object and return an HttpResponse object. Django views are simple callables that take an HttpRequest instance and return an HttpResponse. Decorators are optional, the file name is convention, and querysets are an internal implementation detail, not a requirement for the view interface.

    From lesson: Function-Based Views (FBV)

  27. If you need to handle both GET and POST requests in the same FBV, what is the best practice for structuring the code?

    • Create two separate functions and point them to the same URL pattern
    • Use a conditional check on the request method inside a single function
    • Use the @require_http_methods decorator for each request type
    • Perform all logic in the view regardless of the method

    Answer: Use a conditional check on the request method inside a single function. Using a conditional check on 'request.method' is the standard way to handle different request types in FBVs. Two separate functions would require complex URL routing. Decorators are for restricting methods, not handling them differently, and ignoring the method leads to security vulnerabilities.

    From lesson: Function-Based Views (FBV)

  28. Why should you use Django forms or serializers inside an FBV instead of manually parsing request.POST?

    • Because it is required to use the Django template engine
    • Because manual parsing prevents the view from returning an HttpResponse
    • Because they provide automatic sanitization, validation, and error feedback
    • Because Django will throw a runtime error if you don't use them

    Answer: Because they provide automatic sanitization, validation, and error feedback. Forms automate the validation and sanitization of incoming data, which is essential for security and reducing boilerplate. Manually parsing is possible but prone to errors, and it is not a technical requirement for returning a response.

    From lesson: Function-Based Views (FBV)

  29. How does an FBV obtain parameters passed from the URL pattern (e.g., /user/<int:id>/)?

    • They are automatically passed as additional keyword arguments to the function
    • They are accessible via the request.GET dictionary
    • They are stored as attributes on the request object
    • They must be manually parsed from the request.path string

    Answer: They are automatically passed as additional keyword arguments to the function. Django's URL dispatcher maps captured groups in the URL pattern to the function arguments of the view. The other options are incorrect because the parameters are not automatically in GET data, are not request attributes, and manual parsing is unnecessary.

    From lesson: Function-Based Views (FBV)

  30. What happens if a view function finishes execution without returning anything?

    • Django returns a default 404 error
    • Django renders the last used template automatically
    • Django raises a ValueError because the view must return an HttpResponse
    • The browser displays a blank white page

    Answer: Django raises a ValueError because the view must return an HttpResponse. Django strictly requires views to return an HttpResponse object. If the function returns 'None', Django catches this at runtime and raises a ValueError to prevent unexpected behavior. The other options imply incorrect automatic recovery.

    From lesson: Function-Based Views (FBV)

  31. When building a view that handles both displaying a form and processing a submission, why is it better to use FormView rather than a manual function or custom CBV?

    • FormView automatically converts the request into a JSON response.
    • It provides standardized methods like 'form_valid' and 'form_invalid' that handle redirects and error re-rendering automatically.
    • It is the only way to ensure the database transactions remain isolated from the user session.
    • It bypasses the need for Django's middleware stack, increasing performance.

    Answer: It provides standardized methods like 'form_valid' and 'form_invalid' that handle redirects and error re-rendering automatically.. FormView handles the complex logic of checking if a request is GET or POST, validating forms, and redirecting on success. Option 0 is false as it returns HTML; option 2 is irrelevant to views; option 3 is false as middleware is essential.

    From lesson: Class-Based Views (CBV)

  32. What is the primary purpose of the 'dispatch' method in a Django Class-Based View?

    • To manage the lifecycle of the database connection for that specific request.
    • To serve as the entry point that determines which HTTP method (GET, POST, etc.) should handle the request.
    • To automatically serialize the response into a template before sending it to the user.
    • To define the specific URL path pattern that the class is allowed to handle.

    Answer: To serve as the entry point that determines which HTTP method (GET, POST, etc.) should handle the request.. The 'dispatch' method inspects the request method and routes it to the corresponding method in the class (like 'get' or 'post'). Option 0, 2, and 3 describe other framework components.

    From lesson: Class-Based Views (CBV)

  33. When overriding 'get_queryset' in a 'ListView', what is the most important constraint to ensure data integrity?

    • The method must return a list of Python dictionaries instead of a QuerySet object.
    • The returned QuerySet must be filtered by the currently authenticated user to ensure data privacy.
    • The method must always return the entire table to prevent performance bottlenecks.
    • You must explicitly call the 'save()' method on the QuerySet before returning it.

    Answer: The returned QuerySet must be filtered by the currently authenticated user to ensure data privacy.. In most applications, it is vital to restrict 'get_queryset' to objects belonging to the user. Option 0 is wrong as ListView expects a manager/queryset; option 2 is inefficient; option 3 is invalid as QuerySets are lazy.

    From lesson: Class-Based Views (CBV)

  34. Why should you avoid storing stateful information (like the current user's progress) as instance variables on a CBV class?

    • Django re-instantiates the class for every incoming request.
    • Django caches class instances, so instance variables might be shared between different users' requests.
    • Instance variables can only be stored if they are declared as static class attributes.
    • The Django template engine cannot access variables defined on the class instance.

    Answer: Django caches class instances, so instance variables might be shared between different users' requests.. Because Django reuse views, class instances are often long-lived. Storing user-specific data in 'self' variables can lead to data leakage between users. The other options are either false or incorrect regarding Django internals.

    From lesson: Class-Based Views (CBV)

  35. If you need to pass additional data to your template that isn't derived from a model, which method is the standard place to do this?

    • __init__
    • get_context_data
    • render_to_response
    • setup

    Answer: get_context_data. 'get_context_data' is specifically designed to merge additional data into the dictionary provided to the template. '__init__' is too early, 'setup' is for request initialization, and 'render_to_response' is typically handled by the base classes.

    From lesson: Class-Based Views (CBV)

  36. When using a ListView, how does Django determine the queryset of objects to display?

    • It looks for a function named get_all_objects in the view.
    • It uses the 'model' attribute to call .objects.all() by default.
    • It requires a manual SQL query defined in the __init__ method.
    • It automatically fetches all objects from the database regardless of the model attribute.

    Answer: It uses the 'model' attribute to call .objects.all() by default.. Django defaults to model.objects.all() if the 'model' attribute is set. Option 0 is wrong because no such function exists. Option 2 is wrong because Django abstracts SQL. Option 3 is wrong because the 'model' attribute is mandatory for the default behavior.

    From lesson: Generic Views — ListView, DetailView, CreateView

  37. What is the primary purpose of overriding 'get_queryset' in a ListView?

    • To define the template file path for the view.
    • To add static context data to the template.
    • To filter or order the objects retrieved from the database.
    • To manually handle the HTTP POST request logic.

    Answer: To filter or order the objects retrieved from the database.. get_queryset allows you to refine the initial query, such as filtering by the current user. Option 0 is handled by 'template_name'. Option 1 is handled by 'get_context_data'. Option 3 is irrelevant as ListView is primarily for GET requests.

    From lesson: Generic Views — ListView, DetailView, CreateView

  38. In a CreateView, what is the safest way to ensure an object is associated with the currently logged-in user?

    • Include the user field in the 'fields' list of the form.
    • Override 'form_valid' to set the user attribute on the instance before saving.
    • Set the 'user' attribute directly on the class-level model definition.
    • Use a hidden input field in the HTML template for the user ID.

    Answer: Override 'form_valid' to set the user attribute on the instance before saving.. Overriding form_valid allows you to access the request object safely. Option 0 is insecure as users could change the value. Option 2 is impossible as the user isn't global. Option 3 is a security risk as hidden fields can be manipulated by users.

    From lesson: Generic Views — ListView, DetailView, CreateView

  39. If you define both 'fields' and 'form_class' in a CreateView, which one does Django prioritize?

    • It prioritizes 'fields' because it is more specific.
    • It raises an ImproperlyConfigured exception.
    • It prioritizes 'form_class' because it allows more customization.
    • It merges them into a single form instance.

    Answer: It raises an ImproperlyConfigured exception.. Django requires one or the other, but not both, as they conflict in how the form is instantiated. Option 0 and 2 are incorrect because the view explicitly checks for this conflict. Option 3 is incorrect as they represent different configuration strategies.

    From lesson: Generic Views — ListView, DetailView, CreateView

  40. Why is the DetailView automatically capable of fetching the correct object from the database?

    • It uses the 'pk' or 'slug' keyword argument passed from the URL configuration.
    • It scans the entire database for a matching ID.
    • It uses a browser cookie to store the last accessed ID.
    • It creates a temporary table for every request.

    Answer: It uses the 'pk' or 'slug' keyword argument passed from the URL configuration.. DetailView uses URL parameters like pk or slug to look up objects. Option 1 is inefficient and not how Django works. Option 2 is incorrect as HTTP is stateless. Option 3 is incorrect as generic views do not create database tables during requests.

    From lesson: Generic Views — ListView, DetailView, CreateView

  41. Which statement best describes how DTL handles method calls compared to Jinja2?

    • DTL automatically executes any method found on an object, while Jinja2 requires explicit triggers.
    • DTL restricts method calls to prevent logic-heavy templates, whereas Jinja2 allows direct execution with arguments.
    • Both systems allow unrestricted method calling for maximum flexibility.
    • Both systems forbid method calls entirely to ensure template safety.

    Answer: DTL restricts method calls to prevent logic-heavy templates, whereas Jinja2 allows direct execution with arguments.. DTL is designed to be logic-less and prevents passing arguments to methods to keep business logic in the views. Jinja2 allows this explicitly. Option 0 and 2 are incorrect because DTL is restrictive. Option 3 is false because DTL does allow some attribute access.

    From lesson: Jinja2 vs Django Template Language

  42. If you need to iterate over a dictionary and access both keys and values, which syntax is more idiomatic in DTL?

    • for key, value in my_dict.items
    • for key in my_dict: {{ my_dict[key] }}
    • for key, value in my_dict.items()
    • for loop in my_dict.values()

    Answer: for key, value in my_dict.items. DTL uses the '.items' attribute to access dictionary pairs without parentheses. Option 2 is invalid syntax in DTL. Option 1 uses parentheses, which causes an error in DTL. Option 3 only retrieves values, not keys.

    From lesson: Jinja2 vs Django Template Language

  43. Why does DTL favor the use of template tags over simple Python expressions?

    • Because Python expressions are faster to parse than tags.
    • To ensure that templates remain readable and maintainable by non-Python developers.
    • Because DTL is natively built on a compiled C language.
    • To allow direct access to the entire Python standard library within the template.

    Answer: To ensure that templates remain readable and maintainable by non-Python developers.. DTL's primary philosophy is that template designers should not have to be Python programmers. Restricting code to specific tags enforces this. Option 0 is false, option 2 is irrelevant, and option 3 is the exact opposite of DTL's security model.

    From lesson: Jinja2 vs Django Template Language

  44. What happens if you try to access a missing key in a dictionary using DTL versus Jinja2?

    • Both will raise a KeyError and crash the server.
    • DTL returns an empty string (or silent failure), while Jinja2 defaults to 'None'.
    • DTL crashes immediately, while Jinja2 ignores it.
    • Both are configurable, but default to rendering the literal string 'None'.

    Answer: DTL returns an empty string (or silent failure), while Jinja2 defaults to 'None'.. DTL is designed for silent failure to prevent crashes on missing data, while Jinja2's default behavior is to return 'None' (or 'undefined') which is often explicitly handled. Option 0 and 2 are incorrect because they don't describe the silent failure. Option 3 is incorrect because DTL does not crash.

    From lesson: Jinja2 vs Django Template Language

  45. When defining a reusable UI component, what is the core advantage of Jinja2 macros over DTL include tags?

    • Macros are faster to render because they are stored in the database.
    • Macros allow passing arguments like a function, while includes rely on global context.
    • Includes are deprecated in modern Django.
    • Macros automatically convert all variables to string objects for safety.

    Answer: Macros allow passing arguments like a function, while includes rely on global context.. Jinja2 macros behave like functions and accept arguments, allowing for local scope and high reusability. DTL includes generally inherit the parent context, making them less encapsulated. Options 0, 2, and 3 are factually incorrect regarding framework functionality.

    From lesson: Jinja2 vs Django Template Language

  46. If you need to perform a complex calculation using two model fields before rendering, what is the most 'Django-pythonic' approach?

    • Write a custom template tag that takes both fields as arguments
    • Perform the calculation in the view or add a method to the model and access it in the template
    • Use nested 'with' tags to calculate the value inside the HTML
    • Create a complex custom filter that chains the two fields together

    Answer: Perform the calculation in the view or add a method to the model and access it in the template. Moving logic to the model or view maintains the separation of concerns. Custom tags are for UI elements, not data processing. 'With' tags are for aliasing, not heavy logic, and chaining filters is inefficient and unreadable.

    From lesson: Template Tags and Filters

  47. Why does Django prevent you from calling {{ user.get_full_name() }} in a template?

    • Because it is technically difficult to implement in the Python interpreter
    • To enforce the philosophy that templates should be devoid of business logic
    • Because template variables must be attributes, not methods
    • To prevent developers from accidentally running database queries from the UI

    Answer: To enforce the philosophy that templates should be devoid of business logic. Django intentionally limits template capability to ensure logic stays in views. Option 3 is false (Django can call methods if they have no arguments), and 4 is a side effect, not the design goal. 1 is incorrect as Python handles it easily.

    From lesson: Template Tags and Filters

  48. You have a custom tag 'my_tag'. Which line must appear at the top of your HTML file for it to work?

    • {% load my_tag %}
    • {% import my_tag %}
    • {% include 'templatetags/my_tag.py' %}
    • {% load my_tag from templatetags %}

    Answer: {% load my_tag %}. In Django, you load the module containing your tags by name using the 'load' tag. Option 1 is the correct syntax. The others are invalid syntax or conceptually incorrect for how the template engine discovers tags.

    From lesson: Template Tags and Filters

  49. How do you pass a second argument to a custom filter named 'my_filter'?

    • {{ value|my_filter:arg1,arg2 }}
    • {{ value|my_filter(arg1) }}
    • {{ value|my_filter:'some_string' }}
    • {{ value|my_filter=arg1 }}

    Answer: {{ value|my_filter:'some_string' }}. Filters only accept one argument after the pipe, passed via a colon. Option 0 is invalid syntax. Option 1 mimics Python function calls which is not allowed. Option 3 uses assignment which is invalid.

    From lesson: Template Tags and Filters

  50. What happens if a variable in a template does not exist in the provided context?

    • Django throws a TemplateDoesNotExist exception
    • The template engine renders an empty string by default
    • The entire page renders an error message
    • The application crashes with a NameError

    Answer: The template engine renders an empty string by default. By default, Django silently fails on missing variables and renders an empty string. Option 0 refers to files, not variables. Options 2 and 3 would make websites unusable for users in production, so Django avoids them.

    From lesson: Template Tags and Filters

  51. If you want to append content to a block defined in a base template rather than replacing it entirely, what should you do?

    • Use the {% append %} tag inside the child template
    • Call the block.super variable inside the child block
    • Define the block twice in the child template
    • Use the {% include %} tag for the base template

    Answer: Call the block.super variable inside the child block. block.super is the correct way to render the contents of the parent block within the child. The other options are incorrect: append tags do not exist, defining blocks twice will cause issues, and include is for partials, not inheritance.

    From lesson: Template Inheritance

  52. What happens if a child template tries to override a block that does not exist in the base template?

    • Django throws a TemplateDoesNotExist error
    • The child template crashes at runtime
    • The content is simply ignored by the rendering engine
    • Django automatically creates the block in the base template

    Answer: The content is simply ignored by the rendering engine. If a block tag is not defined in the parent, Django ignores it silently. It does not crash, nor does it create the block. Errors only occur if the extends tag itself points to a missing file.

    From lesson: Template Inheritance

  53. Why is the {% extends %} tag required to be the first tag in a template file?

    • It is a strict requirement of the Python interpreter
    • It allows Django to immediately identify the parent-child relationship during parsing
    • It prevents the template from inheriting from multiple base templates
    • It ensures that CSS files are loaded before the HTML content

    Answer: It allows Django to immediately identify the parent-child relationship during parsing. Django requires {% extends %} to be the first template tag because it dictates the structure of the entire rendering process. If placed later, the engine has already started parsing non-inheritance elements. It has nothing to do with Python or CSS loading.

    From lesson: Template Inheritance

  54. Which of the following is true about how Django handles template inheritance depth?

    • Templates can only extend one level deep
    • Templates are limited to three levels of inheritance
    • Templates can extend infinitely as long as the hierarchy is linear
    • Inheritance is restricted to the same directory as the base template

    Answer: Templates can extend infinitely as long as the hierarchy is linear. Django supports multi-level inheritance, meaning a child can extend a parent, which in turn extends a grand-parent. There is no limit to the depth, nor are you restricted by directory location.

    From lesson: Template Inheritance

  55. What is the primary purpose of defining a block in a base template?

    • To define a region that child templates can override or populate
    • To force the child template to load specific JavaScript libraries
    • To define a static global variable for the entire application
    • To increase the speed at which the base template is parsed by the server

    Answer: To define a region that child templates can override or populate. Blocks act as placeholders in the parent template that child templates fill in. The other options are incorrect as blocks have no effect on variable scope, JS loading, or rendering performance optimization.

    From lesson: Template Inheritance

  56. What is the primary difference between how Django handles 'static' files versus 'media' files?

    • Static files are uploaded by users, while media files are part of the site design.
    • Static files are served from STATIC_ROOT during development, while media requires a database.
    • Static files are static assets that are part of the codebase, whereas media files are uploaded by users at runtime.
    • Media files must be processed by the collectstatic command, while static files are processed by the MEDIA_URL setting.

    Answer: Static files are static assets that are part of the codebase, whereas media files are uploaded by users at runtime.. Static files are deployment-time assets (CSS/JS), while media files are runtime user uploads. Option 0 is reversed. Option 1 is incorrect because Django doesn't serve from STATIC_ROOT in development. Option 3 is incorrect as collectstatic does not handle media.

    From lesson: Static Files and Media

  57. When working in a local development environment, why is it necessary to add the static URL path to your urls.py?

    • Because the Django development server does not automatically serve static files from all locations without configuration.
    • Because the browser requires a database entry to locate the local CSS files.
    • Because otherwise, the collectstatic command will fail to create the folder structure.
    • Because Django is unable to find the settings.py file without an explicit URL mapping.

    Answer: Because the Django development server does not automatically serve static files from all locations without configuration.. In development, Django needs explicit instructions to map static URLs to the file system. Option 1 is false (DB is not involved). Option 2 is false (collectstatic is not for dev). Option 3 is false (settings are handled by the environment).

    From lesson: Static Files and Media

  58. Why should you use the {% static %} template tag instead of hardcoded paths?

    • It automatically compresses your CSS and JS files for better performance.
    • It prepends the STATIC_URL setting to your path, making the URL dynamic and configurable.
    • It validates that the file exists on the server before rendering the HTML.
    • It allows you to switch between different database backends automatically.

    Answer: It prepends the STATIC_URL setting to your path, making the URL dynamic and configurable.. The tag ensures that if you change your STATIC_URL configuration (e.g., to a CDN), your links update automatically. Other options describe features not performed by the static tag.

    From lesson: Static Files and Media

  59. If you are running collectstatic, which directory is populated with files gathered from your apps and STATICFILES_DIRS?

    • MEDIA_ROOT
    • STATICFILES_FINDERS
    • STATIC_ROOT
    • TEMPLATE_DIRS

    Answer: STATIC_ROOT. STATIC_ROOT is specifically designed to be the destination for the collectstatic command. MEDIA_ROOT is for uploads, and the others are not file-gathering destination paths.

    From lesson: Static Files and Media

  60. If an image uploaded by a user is saved to MEDIA_ROOT, what is the best practice for displaying this image in a template?

    • Use the {% static %} tag referencing the media file path.
    • Use the image's URL attribute combined with the MEDIA_URL setting.
    • Directly use the file system absolute path to ensure the browser finds the image.
    • Move the file to the STATIC_ROOT folder so that the static tag can find it.

    Answer: Use the image's URL attribute combined with the MEDIA_URL setting.. Media files are served via MEDIA_URL. Static tags are for application assets, not user uploads. Using system paths is a security risk and won't work in browsers. Moving files to STATIC_ROOT is incorrect as users should not modify production static directories.

    From lesson: Static Files and Media

  61. When you want to allow a field to be empty in a form submission but keep the database column non-nullable, which configuration should you use?

    • null=True, blank=False
    • null=False, blank=True
    • null=True, blank=True
    • null=False, blank=False

    Answer: null=False, blank=True. Option 2 is correct because blank=True allows the Django form validator to accept an empty field, while null=False ensures the database requires a value, fitting the string-field convention. Option 1 is invalid (you cannot have blank=False if null=True), Option 3 allows NULLs in the DB which is discouraged for strings, and Option 4 makes the field mandatory.

    From lesson: Defining Models and Fields

  62. What happens if you define two ForeignKey fields pointing to the User model in the same class without specifying 'related_name'?

    • The migration will succeed, but the reverse relationship will only point to the last defined field.
    • The migration will fail with a 'Reverse accessor clash' error during system checks.
    • Django will automatically append a suffix like _1 and _2 to the related names.
    • Both fields will share the same reverse manager, causing data integrity issues.

    Answer: The migration will fail with a 'Reverse accessor clash' error during system checks.. Django requires a unique reverse accessor for every relationship. If two fields target the same model without a custom 'related_name', the system check detects a collision and throws an error to prevent ambiguity. Option 3 is incorrect because Django does not automatically rename, and options 1 and 4 are physically prevented by the framework's startup checks.

    From lesson: Defining Models and Fields

  63. Why is it recommended to use a custom model instead of the default auth.User for authentication?

    • The default User model is missing common fields like email and password.
    • Modifying the default model creates conflicts with third-party libraries.
    • It provides total control over the authentication process and identity fields before you start your project.
    • Custom models are faster at database lookups than the built-in auth User.

    Answer: It provides total control over the authentication process and identity fields before you start your project.. Option 3 is correct; changing the User model after migrations have run is notoriously difficult, so setting it up at the start is best practice. Option 1 is false (User has those fields). Option 2 is partly true but not the primary reason. Option 4 is false, as there is no significant performance difference.

    From lesson: Defining Models and Fields

  64. Which field type should you use to store a large amount of text content that might exceed the capacity of a standard database column?

    • CharField
    • TextField
    • BinaryField
    • SlugField

    Answer: TextField. TextField is specifically designed for arbitrary-length text. CharField requires a 'max_length' which limits size. BinaryField is for raw bytes, and SlugField is intended for short, URL-friendly strings, making them inappropriate for large text blocks.

    From lesson: Defining Models and Fields

  65. If you define a custom method in a model, why is it safer to use 'self' rather than accessing the model class directly?

    • Using 'self' ensures the method works on specific model instances rather than the table as a whole.
    • Accessing the model class directly is forbidden by Python's private scope rules.
    • It allows the method to work even if the class is renamed during refactoring.
    • Methods without 'self' are automatically converted to class methods by Django's ORM.

    Answer: Using 'self' ensures the method works on specific model instances rather than the table as a whole.. Option 0 is correct: instance methods operate on the specific data of one row, whereas class-level access would attempt to operate on the entire table. The other options are incorrect as they misrepresent Python scoping and Django's internal class handling.

    From lesson: Defining Models and Fields

  66. What is the primary purpose of running the 'makemigrations' command?

    • To apply changes directly to the database engine
    • To create Python files that represent changes to model definitions
    • To synchronize the database schema with the model changes automatically
    • To verify if the database connection settings are correct

    Answer: To create Python files that represent changes to model definitions. Makemigrations strictly generates migration files (instructions). It does not interact with the database. The other options describe the 'migrate' command or general diagnostic checks.

    From lesson: Migrations — makemigrations and migrate

  67. If you rename a model field in your models.py file and run 'makemigrations', what will Django do?

    • Automatically detect the rename and prepare to update the database column
    • Delete the old column and create a new one, potentially losing data
    • Throw an error because the field names must match the database exactly
    • Ignore the change because field names are not tracked in migrations

    Answer: Automatically detect the rename and prepare to update the database column. Django tracks fields via IDs, so it detects a rename and prompts for an instruction to 'rename field'. It does not delete data (option 1 is right). Options 2, 3, and 4 are incorrect because Django is designed to handle schema evolution safely.

    From lesson: Migrations — makemigrations and migrate

  68. Why might you receive a 'Migration applied but does not exist' error?

    • Because you ran 'migrate' without running 'makemigrations'
    • Because the database schema is newer than the codebase
    • Because migration files recorded in the database were deleted from the file system
    • Because you are using an unsupported database backend

    Answer: Because migration files recorded in the database were deleted from the file system. This error occurs when the 'django_migrations' table records a file, but the physical file is missing. Option 1 leads to schema divergence, not this specific error; 2 and 4 are unrelated to migration file existence.

    From lesson: Migrations — makemigrations and migrate

  69. When is it appropriate to use the 'migrate --fake' command?

    • When you want to reset your database to a blank state
    • When you have manually updated the database schema and want Django to acknowledge it
    • When you want to test if your migrations will work without changing the database
    • When you have multiple developers and want to bypass migration checks

    Answer: When you have manually updated the database schema and want Django to acknowledge it. The --fake flag updates the migration tracking table without executing SQL, which is perfect for when the database and code are already in sync. The other options are misuse cases that could lead to data corruption or inconsistency.

    From lesson: Migrations — makemigrations and migrate

  70. What happens if two developers generate separate migration files for the same model at the same time?

    • Django automatically merges them into one file during the next run
    • The database will automatically resolve the conflict at runtime
    • Both migrations will exist, but they may conflict, leading to an 'InconsistentMigrationHistory' error
    • The migration system will block the merge request until one developer deletes their file

    Answer: Both migrations will exist, but they may conflict, leading to an 'InconsistentMigrationHistory' error. Django treats migration files as a sequential chain. Divergent chains cause conflicts. Options 1 and 4 are incorrect as Django does not perform automated complex merges, and 2 is incorrect as the database has no knowledge of migration file history.

    From lesson: Migrations — makemigrations and migrate

  71. You want to find all 'Books' where the 'author' is either 'John' OR the 'genre' is 'Sci-Fi'. Which approach is correct?

    • Book.objects.filter(author='John').filter(genre='Sci-Fi')
    • Book.objects.filter(Q(author='John') | Q(genre='Sci-Fi'))
    • Book.objects.exclude(author!='John', genre!='Sci-Fi')
    • Book.objects.filter(author='John').union(Book.objects.filter(genre='Sci-Fi'))

    Answer: Book.objects.filter(Q(author='John') | Q(genre='Sci-Fi')). Option 2 uses Q objects with the pipe operator, which is the standard way to implement OR logic in Django. Option 1 implements AND logic, Option 3 is syntactically incorrect for excluding, and Option 4 performs two separate queries instead of one.

    From lesson: QuerySet API — filter, exclude, annotate

  72. What is the primary difference between annotate() and aggregate()?

    • annotate() returns a single dictionary, while aggregate() returns a QuerySet.
    • annotate() adds a calculated field to every object in the QuerySet, while aggregate() returns a single result for the whole QuerySet.
    • aggregate() is lazy, while annotate() hits the database immediately.
    • annotate() is used only for math, while aggregate() is used for strings.

    Answer: annotate() adds a calculated field to every object in the QuerySet, while aggregate() returns a single result for the whole QuerySet.. annotate() transforms each object in the QuerySet by adding a field, whereas aggregate() calculates a summary value (like a count or sum) over the entire QuerySet and returns a dictionary.

    From lesson: QuerySet API — filter, exclude, annotate

  73. If you have a QuerySet of Products, and you perform 'Product.objects.filter(price__gt=10).annotate(num_reviews=Count('reviews'))', what will the QuerySet contain?

    • All products, with a count of all reviews existing in the database.
    • Only products with price > 10, where num_reviews is the count of reviews for that specific product.
    • Only products with reviews, with their price greater than 10.
    • A dictionary containing the count of reviews for products costing more than 10.

    Answer: Only products with price > 10, where num_reviews is the count of reviews for that specific product.. The filter limits the initial set to products costing over 10, and the annotation counts reviews for each product within that filtered list. Option 1 ignores the filter for the count, Option 3 is inaccurate regarding which products are kept, and Option 4 incorrectly describes the return type.

    From lesson: QuerySet API — filter, exclude, annotate

  74. Why does calling 'exclude(status='archived')' behave unexpectedly on fields that allow NULL values?

    • Because exclude() automatically converts NULL values to empty strings.
    • Because SQL logic treats NULL as neither equal nor unequal, meaning rows with NULL status are excluded from the result set.
    • Because exclude() only works on boolean fields.
    • Because Django defaults all NULL values to 'archived'.

    Answer: Because SQL logic treats NULL as neither equal nor unequal, meaning rows with NULL status are excluded from the result set.. In SQL, NULL comparisons evaluate to 'Unknown'. Therefore, 'status != 'archived'' is false for NULL rows. Consequently, exclude() omits these records. The other options are false assertions about how Django or SQL handles nulls.

    From lesson: QuerySet API — filter, exclude, annotate

  75. Which statement best describes the execution of a QuerySet?

    • A QuerySet is executed as soon as the filter() method is called.
    • A QuerySet is only executed when it is evaluated (e.g., iterated, sliced, or printed).
    • A QuerySet executes once per chained method call.
    • A QuerySet must be converted to a list before any filter() or exclude() can be applied.

    Answer: A QuerySet is only executed when it is evaluated (e.g., iterated, sliced, or printed).. QuerySets are lazy; they don't hit the database until you actually need the data. Option 1 and 3 are wrong because the database is not hit until evaluation. Option 4 is wrong because ORM methods are designed to be chained on QuerySets, not lists.

    From lesson: QuerySet API — filter, exclude, annotate

  76. You have a 'Book' model with a ForeignKey to an 'Author' model. Which approach is most efficient for displaying a list of 50 books and their authors?

    • Iterate through books and call book.author for each.
    • Use Book.objects.select_related('author').all().
    • Use Book.objects.prefetch_related('author').all().
    • Fetch all authors first, then match them by ID in Python.

    Answer: Use Book.objects.select_related('author').all().. select_related performs a SQL JOIN, fetching the author data in the same query as the book. Option 0 causes N+1 queries. Option 2 is for M2M or reverse FK relationships. Option 3 is manual and inefficient.

    From lesson: Related Objects — ForeignKey, ManyToMany

  77. What is the primary difference between ForeignKey and ManyToManyField in terms of database storage?

    • ForeignKey creates a column in the table, ManyToMany creates a separate join table.
    • ForeignKey requires a join table, while ManyToMany uses a column on both models.
    • There is no difference; both create join tables in the database.
    • ForeignKey is only for one-to-one, while ManyToMany is for many-to-one.

    Answer: ForeignKey creates a column in the table, ManyToMany creates a separate join table.. ForeignKey adds a column to the model's table containing the ID of the related object. ManyToMany requires a 'through' table to store pairings. Option 1, 2, and 3 misidentify the fundamental SQL implementation.

    From lesson: Related Objects — ForeignKey, ManyToMany

  78. When defining a ForeignKey, what is the purpose of the 'on_delete' argument?

    • To define whether the related object can be deleted.
    • To set the behavior of the database when the referenced object is deleted.
    • To automatically delete the parent object when the child is deleted.
    • To check if the related object exists before querying.

    Answer: To set the behavior of the database when the referenced object is deleted.. on_delete determines SQL constraint behavior like CASCADE, PROTECT, or SET_NULL. It does not control object existence or reverse deletion logic.

    From lesson: Related Objects — ForeignKey, ManyToMany

  79. Given an instance 'author' and a ManyToManyField 'books', how do you correctly associate a new book object with the author?

    • author.books.create(title='New Book')
    • author.books = [new_book]
    • author.books.add(new_book)
    • author.add(new_book)

    Answer: author.books.add(new_book). The RelatedManager provides .add() to create the link in the join table. .create() is also valid but adds the instance to the database, whereas .add() is specifically for associating existing objects. Option 1 creates a new object; Option 2 replaces the entire collection; Option 3 is incorrect syntax.

    From lesson: Related Objects — ForeignKey, ManyToMany

  80. Why would you choose to use a custom 'through' model for a ManyToManyField?

    • To make the database queries run faster.
    • To store extra information about the relationship, such as the date joined.
    • To prevent multiple relationships between the same two objects.
    • To remove the need for a join table in the database.

    Answer: To store extra information about the relationship, such as the date joined.. A 'through' model allows you to add fields (like 'date_added' or 'role') to the relationship itself. It does not improve query speed, does not prevent duplicates, and does not eliminate the join table.

    From lesson: Related Objects — ForeignKey, ManyToMany

  81. What is the primary benefit of moving logic from a view or signal into a custom QuerySet method?

    • It increases the execution speed of the database query engine.
    • It improves code reusability and allows for method chaining across different views.
    • It automatically optimizes database indexing for the filtered fields.
    • It prevents the model from being accessed by the default manager.

    Answer: It improves code reusability and allows for method chaining across different views.. Moving logic to QuerySet methods allows you to chain filters, which is the core strength of the Django ORM. The other options are incorrect because logic placement does not speed up the engine, affect indexing, or restrict access to the default manager.

    From lesson: Custom Managers and QuerySets

  82. You have a custom manager with a method 'active()'. If you want to chain it like 'Book.objects.active().recent()', what must 'active()' return?

    • A list of model instances.
    • A dictionary of filtered results.
    • A QuerySet instance.
    • A boolean indicating if the operation succeeded.

    Answer: A QuerySet instance.. For Django ORM methods to be chainable, they must return a QuerySet. Returning lists or other types terminates the chain and breaks the ability to append further filters or orderings.

    From lesson: Custom Managers and QuerySets

  83. When defining a custom manager, why should you use .as_manager() when you have a custom QuerySet?

    • It creates a manager that automatically includes all methods defined in your custom QuerySet.
    • It forces the manager to ignore the database and work only in memory.
    • It tells Django to ignore the model's base class attributes.
    • It increases the default timeout for queries performed by that manager.

    Answer: It creates a manager that automatically includes all methods defined in your custom QuerySet.. .as_manager() is a convenience method that takes the methods defined on your custom QuerySet and adds them to the manager, making them accessible directly from the model, enabling the chainable syntax.

    From lesson: Custom Managers and QuerySets

  84. If you override 'get_queryset()' in a custom manager, what is the best practice to ensure you don't lose the base functionality?

    • Copy and paste the entire source code of the default manager's get_queryset.
    • Hardcode the model class name inside the get_queryset method.
    • Call super().get_queryset() and then apply your custom filters.
    • Instantiate a new QuerySet class from scratch without calling the super method.

    Answer: Call super().get_queryset() and then apply your custom filters.. Calling super().get_queryset() ensures you inherit the standard base QuerySet that is correctly initialized with the model class. The other options either create unnecessary code duplication or risk initializing the QuerySet incorrectly.

    From lesson: Custom Managers and QuerySets

  85. Which of the following is true regarding 'use_in_migrations' on a custom manager?

    • It allows the manager to be serialized and used in migration files.
    • It automatically adds an 'is_active' field to your model.
    • It forces the database to recreate all indexes every time a migration runs.
    • It is required for every custom manager, or migrations will fail.

    Answer: It allows the manager to be serialized and used in migration files.. The 'use_in_migrations' flag allows Django's migration framework to see and use your custom manager when generating migrations. It is not mandatory, and the other options describe behavior unrelated to the migration system.

    From lesson: Custom Managers and QuerySets

  86. Which setting is required to successfully implement a custom user model in a Django project?

    • A custom middleware class in settings.py
    • The AUTH_USER_MODEL setting pointing to the app.Model string
    • A custom authentication backend class in settings.py
    • Adding the user model to the INSTALLED_APPS list only

    Answer: The AUTH_USER_MODEL setting pointing to the app.Model string. AUTH_USER_MODEL is the specific setting Django looks for to know which model acts as the user; the others are either unnecessary or incorrect configurations for model swapping.

    From lesson: Django Auth — User Model, Login, Logout

  87. What is the primary difference between the authenticate() and login() functions?

    • authenticate() creates the session, while login() verifies credentials.
    • authenticate() checks if the user exists in the DB, while login() attaches the user to the current request session.
    • They are identical functions that perform the same task.
    • login() is only for web forms, while authenticate() is only for APIs.

    Answer: authenticate() checks if the user exists in the DB, while login() attaches the user to the current request session.. authenticate() verifies credentials against the database but does not change the request state, while login() is responsible for establishing the session associated with the request.

    From lesson: Django Auth — User Model, Login, Logout

  88. When building a custom User model, why is AbstractUser preferred over AbstractBaseUser for most developers?

    • AbstractUser includes all default Django auth fields and permissions, requiring less boilerplate.
    • AbstractBaseUser is deprecated and will be removed in future versions.
    • AbstractUser is faster to query in the database than AbstractBaseUser.
    • AbstractBaseUser does not support password hashing.

    Answer: AbstractUser includes all default Django auth fields and permissions, requiring less boilerplate.. AbstractUser provides a full implementation including username, email, and permissions, whereas AbstractBaseUser requires you to implement these features from scratch.

    From lesson: Django Auth — User Model, Login, Logout

  89. In a view, how should you correctly log out an authenticated user?

    • Delete the user object from the database.
    • Set request.user to None.
    • Call the logout(request) function.
    • Clear the session cache using Session.objects.all().delete().

    Answer: Call the logout(request) function.. The logout(request) function handles clearing the session data and resetting the request user safely, whereas manually manipulating request.user or the session table does not ensure all security cleanups occur.

    From lesson: Django Auth — User Model, Login, Logout

  90. Why is it best practice to use the @login_required decorator rather than manually checking request.user.is_authenticated inside every view?

    • The decorator is faster at executing than an if-statement.
    • It prevents unauthorized access to the view logic by redirecting users automatically.
    • Manual checks are not supported by the template engine.
    • It automatically upgrades the user session to HTTPS.

    Answer: It prevents unauthorized access to the view logic by redirecting users automatically.. The decorator acts as a centralized security gate that prevents the view function from even running if the user is not authenticated, enforcing DRY (Don't Repeat Yourself) principles.

    From lesson: Django Auth — User Model, Login, Logout

  91. Why is it recommended to define a custom User model at the start of a project?

    • It improves the performance of database queries globally
    • Changing it later requires complex manual migrations and data migration scripts
    • It is required by the Django security framework to enable encryption
    • It automatically optimizes the template rendering engine

    Answer: Changing it later requires complex manual migrations and data migration scripts. Changing the User model later is difficult because Django's ORM and foreign keys depend on the User model structure. Options 0, 2, and 3 are incorrect because user model selection does not inherently affect performance, security, or template rendering speed.

    From lesson: Custom User Model

  92. What is the primary difference between AbstractUser and AbstractBaseUser?

    • AbstractUser provides full auth fields; AbstractBaseUser provides only the essential infrastructure
    • AbstractUser is used for admin users; AbstractBaseUser is used for standard users
    • AbstractBaseUser includes built-in email validation; AbstractUser requires custom logic
    • There is no functional difference; they are aliases for the same class

    Answer: AbstractUser provides full auth fields; AbstractBaseUser provides only the essential infrastructure. AbstractUser includes all the default Django User fields (username, email, etc.), while AbstractBaseUser only includes the password and last_login fields, requiring manual implementation of other fields. Options 1, 2, and 3 are factually incorrect.

    From lesson: Custom User Model

  93. When using AbstractBaseUser, which mixin must you include if you want to use the Django Admin interface's permission system?

    • AdminMixin
    • PermissionMixin
    • PermissionsMixin
    • UserAdmin

    Answer: PermissionsMixin. PermissionsMixin adds the fields and methods necessary for Django's permission and group management. Option 0 and 1 are not standard mixins, and Option 3 is a model admin class, not a mixin for the User model.

    From lesson: Custom User Model

  94. If you are replacing the default 'username' with 'email' for authentication, what must you update in your UserManager?

    • The AUTH_USER_MODEL variable in the manager
    • The REQUIRED_FIELDS list to include username
    • The USERNAME_FIELD attribute to point to 'email'
    • The authenticate() method to manually query the database

    Answer: The USERNAME_FIELD attribute to point to 'email'. USERNAME_FIELD defines the unique identifier for the user. Setting it to 'email' tells Django to use that field for authentication. Options 0, 1, and 3 do not correctly facilitate switching the primary authentication identifier.

    From lesson: Custom User Model

  95. What happens if you define a custom User model but fail to update AUTH_USER_MODEL in settings.py?

    • The project will crash immediately upon startup
    • Django will use the default User model, ignoring your custom one
    • The admin panel will display both user models side-by-side
    • The database will automatically merge your fields into the default model

    Answer: Django will use the default User model, ignoring your custom one. If AUTH_USER_MODEL is not set, Django defaults to 'auth.User'. It does not merge fields or crash immediately. Options 0, 2, and 3 describe behaviors that do not occur in the Django framework.

    From lesson: Custom User Model

  96. If you add a new model 'Project' to 'myapp', when are the 'add_project', 'change_project', 'delete_project', and 'view_project' permissions created?

    • Immediately upon saving the models.py file
    • When the user logs into the admin interface
    • During the migration process that creates the database table for the model
    • Only when you explicitly run 'python manage.py createsuperuser'

    Answer: During the migration process that creates the database table for the model. Permissions are tied to the database schema. Migrations create these entries in the 'auth_permission' table. Option 0 and 1 are incorrect because Django does not dynamically generate these based on file existence or login. Option 3 is irrelevant to model permission generation.

    From lesson: Permissions and Groups

  97. A user is a member of two groups. Group A has 'add_post' permission, and Group B has 'delete_post' permission. Does the user have 'change_post' permission?

    • Yes, because they are in groups
    • No, permissions are not additive between groups
    • Yes, but only if they are a superuser
    • No, because neither group explicitly grants 'change_post'

    Answer: No, because neither group explicitly grants 'change_post'. Django's permission system is additive but specific. A user gains all permissions granted to all groups they belong to. Since 'change_post' was not granted to either group, the user does not have it. Option 0 and 2 are incorrect assumptions about how group logic functions.

    From lesson: Permissions and Groups

  98. What is the most efficient way to check if a logged-in user can edit a specific model instance?

    • Check if user.is_staff is true
    • Verify user.groups.all() for an 'Editor' group
    • Use user.has_perm('app.change_modelname')
    • Use user.is_superuser

    Answer: Use user.has_perm('app.change_modelname'). has_perm is the standard, secure way to check specific model permissions. Checking groups (Option 1) is brittle if the group name changes. is_staff (Option 0) and is_superuser (Option 3) are too broad and ignore granular permission settings.

    From lesson: Permissions and Groups

  99. Why might a user be unable to perform an action despite having the correct permission assigned?

    • The user must be manually added to the 'auth_user_groups' table
    • The 'is_active' flag on the user object is set to False
    • Permissions take 24 hours to propagate in the cache
    • The user's password must be re-hashed

    Answer: The 'is_active' flag on the user object is set to False. In Django, users with 'is_active=False' cannot authenticate or have their permissions evaluated as valid. Options 0, 2, and 3 are technically incorrect; Django does not cache permissions by default in this way, nor is a password re-hash required.

    From lesson: Permissions and Groups

  100. When using the 'permission_required' decorator on a view, what happens if the user is not logged in?

    • The view proceeds because they are a guest
    • A 403 Forbidden error is returned
    • The user is redirected to the login page
    • The system throws an UnauthenticatedError

    Answer: The user is redirected to the login page. By default, 'permission_required' checks for authentication; if not met, it triggers a redirect to the login URL. Option 0 is a security risk. Option 1 is incorrect because it redirects first. Option 3 is not a standard Django error.

    From lesson: Permissions and Groups

  101. What is the primary advantage of using a ModelSerializer over a standard Serializer?

    • It provides automatic field generation and default implementations for create and update methods.
    • It ensures the database schema always matches the API schema automatically.
    • It allows direct manipulation of the underlying database cursor for faster queries.
    • It automatically adds authentication decorators to all API endpoints.

    Answer: It provides automatic field generation and default implementations for create and update methods.. Option 0 is correct because ModelSerializer uses the model definition to generate fields and save logic. Option 1 is wrong because model and API schemas are independent. Option 2 is false because serializers do not touch the DB cursor. Option 3 is false as authentication is handled by views, not serializers.

    From lesson: Serializers — ModelSerializer

  102. If you need to include a field from a related model that is not a simple foreign key ID, how should you implement it?

    • Define it as a CharField with a custom source.
    • Use a SerializerMethodField and write a get_<field_name> method.
    • Override the __init__ method of the model.
    • Manually inject the value in the view's get_queryset method.

    Answer: Use a SerializerMethodField and write a get_<field_name> method.. Option 1 is correct because SerializerMethodField allows custom logic for computed or related data. Option 0 won't work without a source mapping. Option 2 is irrelevant to serialization. Option 3 is a violation of the separation of concerns.

    From lesson: Serializers — ModelSerializer

  103. What happens if you set fields = '__all__' in your Meta class?

    • It creates a database migration for all fields.
    • It includes all model fields in the serialization, including hidden ones.
    • It includes all fields defined on the model, including primary keys and relationships.
    • It triggers an error if there are too many fields in the model.

    Answer: It includes all fields defined on the model, including primary keys and relationships.. Option 2 is correct as it maps all model fields to serializer fields. Option 0 is false, serializers don't change migrations. Option 1 is false because it doesn't include hidden fields. Option 3 is false, there is no field limit.

    From lesson: Serializers — ModelSerializer

  104. Why would you choose to override the 'validate' method in a ModelSerializer?

    • To change the structure of the incoming JSON data entirely.
    • To perform complex cross-field validation that depends on multiple model attributes.
    • To force the model to save data to a different database table.
    • To disable the validation of required fields for faster requests.

    Answer: To perform complex cross-field validation that depends on multiple model attributes.. Option 1 is correct because 'validate' is specifically designed for object-level validation. Option 0 is not the intended use of validation. Option 2 is incorrect as ORM logic belongs in the model. Option 3 is dangerous and incorrect.

    From lesson: Serializers — ModelSerializer

  105. When is the 'validated_data' dictionary populated in the serializer lifecycle?

    • Immediately after the object is initialized with data.
    • Only after the is_valid() method is successfully called.
    • Before the request reaches the view's dispatch method.
    • During the model's save process.

    Answer: Only after the is_valid() method is successfully called.. Option 1 is correct because validated_data is only available after validation succeeds. Option 0 is false, as data is raw before validation. Option 2 is false, as the view hasn't reached the serializer yet. Option 3 is false, as save happens after validation.

    From lesson: Serializers — ModelSerializer

  106. When should you prefer using an APIView over a ViewSet in Django REST Framework?

    • When you need full control over the request-response cycle for non-standard endpoints
    • When you want to implement standard CRUD operations for a database model
    • When you want to automatically generate documentation using schemas
    • When you want to reduce the amount of code by using standard routers

    Answer: When you need full control over the request-response cycle for non-standard endpoints. APIView is best for specialized logic where standard CRUD does not apply. The other three options are primary strengths of ViewSets, which automate CRUD and URL generation.

    From lesson: APIView vs ViewSets

  107. What is the primary benefit of using a ViewSet instead of an APIView?

    • ViewSets bypass the middleware stack for faster performance
    • ViewSets allow you to define common behavior once and apply it to multiple HTTP methods
    • ViewSets permit the use of raw SQL queries without serializers
    • ViewSets remove the requirement for authentication classes

    Answer: ViewSets allow you to define common behavior once and apply it to multiple HTTP methods. ViewSets bundle common logic for HTTP methods into a single class, reducing redundancy. Middleware, raw SQL, and authentication are unrelated to the structural benefits of ViewSets.

    From lesson: APIView vs ViewSets

  108. How do you map a URL to a specific action method (e.g., 'mark_as_read') inside a ViewSet?

    • By manually adding path patterns in urls.py for every method
    • By using the @action decorator on the method inside the ViewSet
    • By creating an APIView specifically for that action
    • By defining a custom serializer for the method

    Answer: By using the @action decorator on the method inside the ViewSet. The @action decorator allows you to define custom endpoints within a ViewSet. Manual paths defeat the purpose of ViewSets, and serializers don't define URL endpoints.

    From lesson: APIView vs ViewSets

  109. Why is it often unnecessary to manually write .as_view() when using ViewSets?

    • Because ViewSets use a Router to automatically map actions to URLs
    • Because ViewSets are processed by the template engine
    • Because ViewSets are automatically imported into the settings file
    • Because ViewSets bypass the Django URL resolver entirely

    Answer: Because ViewSets use a Router to automatically map actions to URLs. Routers automatically generate the URL patterns and call .as_view() internally for ViewSets. The other options are factually incorrect regarding how Django or DRF functions.

    From lesson: APIView vs ViewSets

  110. If you are building a simple endpoint that calculates a sum from two inputs without interacting with a database model, which approach is most appropriate?

    • ReadOnlyModelViewSet
    • ModelViewSet
    • APIView
    • GenericViewSet

    Answer: APIView. APIView is designed for custom, non-model-backed logic. The other options (ModelViewSet, ReadOnlyModelViewSet, GenericViewSet) are designed for database interactions and would be overkill or inappropriate.

    From lesson: APIView vs ViewSets

  111. What is the primary advantage of using a Router in Django REST Framework compared to standard path definitions?

    • It provides automatic URL pattern generation based on ViewSet method names
    • It improves the database query performance of the associated view
    • It forces the use of JSON as the only supported content type
    • It automatically secures all endpoints with token authentication

    Answer: It provides automatic URL pattern generation based on ViewSet method names. Routers map ViewSet methods (list, create, retrieve, etc.) to URL patterns automatically. Option 1 is wrong because routers don't affect DB performance. Option 2 is wrong because content negotiation is handled by parsers/renderers. Option 4 is wrong because authentication is handled by permission classes.

    From lesson: Routers

  112. When registering a ViewSet with a Router, why would you need to provide a 'basename' argument?

    • To define the database table name that the view accesses
    • To ensure the URL reversing system can generate unique names for the patterns
    • To override the default HTTP methods permitted for the view
    • To specify the primary key field for the model

    Answer: To ensure the URL reversing system can generate unique names for the patterns. If a ViewSet doesn't have a queryset attribute, the router needs 'basename' to form the prefix for URL names (e.g., 'user-list'). The other options describe model or view configuration that exists independently of the router.

    From lesson: Routers

  113. What is the key difference between SimpleRouter and DefaultRouter?

    • SimpleRouter supports versioning while DefaultRouter does not
    • DefaultRouter includes an API root view and 'format' suffix support
    • SimpleRouter is only for function-based views
    • DefaultRouter requires a database migration to function

    Answer: DefaultRouter includes an API root view and 'format' suffix support. DefaultRouter adds an automatically generated API root and supports .json/.html format suffixes. SimpleRouter lacks these. The other options are incorrect as SimpleRouter works with ViewSets and neither requires specific migrations.

    From lesson: Routers

  114. If you have a ViewSet and want to add an extra action with a specific URL, which decorator should you use, and how does the Router react?

    • Use @action; the router will automatically generate a URL for it
    • Use @method; the router ignores it and requires manual path definitions
    • Use @detail_route; the router will hide the action from the public API
    • Use @custom; the router will block all requests to that endpoint

    Answer: Use @action; the router will automatically generate a URL for it. The @action decorator marks a method to be included in the router's URL generation. 'Method' and 'custom' are not standard decorators for this purpose, and 'detail_route' is deprecated/renamed, not a security block.

    From lesson: Routers

  115. How do you include the URL patterns generated by a router into the main project urls.py?

    • By passing the router object directly to the 'urlpatterns' list
    • By calling 'router.generate_urls()' and passing the result to 'include()'
    • By adding the 'router.urls' list to the 'urlpatterns' list
    • By importing 'router_patterns' from the rest_framework.routers module

    Answer: By adding the 'router.urls' list to the 'urlpatterns' list. Routers expose a 'urls' attribute which is a list of URL patterns that can be appended to the 'urlpatterns' list. The other options suggest syntax that does not exist or is incorrect for Django's URL configuration.

    From lesson: Routers

  116. When a client sends a JWT in the 'Authorization' header, where does Django Rest Framework store the user object after successful authentication?

    • request.user
    • request.session.user
    • request.auth
    • context.user

    Answer: request.user. request.user is the standard attribute where the authenticated user is populated. request.session is not used in stateless JWT authentication, request.auth holds the token object itself, and context.user is not a standard DRF request attribute.

    From lesson: Authentication in DRF — JWT

  117. What is the primary architectural benefit of using JWTs instead of traditional session-based authentication in a DRF API?

    • It eliminates the need for a database lookup for every request.
    • It makes the application stateful by storing tokens on the server.
    • It removes the need for HTTPS encryption.
    • It prevents all forms of CSRF attacks automatically.

    Answer: It eliminates the need for a database lookup for every request.. JWTs allow the server to verify the user without querying the database for session data on every call. It does not make the server stateful, it still requires HTTPS, and it does not inherently prevent CSRF.

    From lesson: Authentication in DRF — JWT

  118. If you need to revoke a specific JWT before its expiration time, what is the best practice approach?

    • Delete the user from the database.
    • Maintain a blacklist or whitelist of JTI (JWT ID) claims in a fast-access cache like Redis.
    • Change the user's password to immediately invalidate all tokens.
    • Change the SECRET_KEY in settings.py.

    Answer: Maintain a blacklist or whitelist of JTI (JWT ID) claims in a fast-access cache like Redis.. Using a blacklist/denylist with JTI claims is the standard way to revoke tokens without destroying the user account or affecting the entire system globally like a SECRET_KEY rotation would.

    From lesson: Authentication in DRF — JWT

  119. Why is it important to use 'IsAuthenticated' as a permission class alongside JWT authentication?

    • JWT only verifies that the token is valid, but does not stop unauthenticated users from hitting endpoints.
    • It is required to decrypt the JWT signature.
    • It forces the client to use a refresh token.
    • Without it, the server will crash on unauthorized requests.

    Answer: JWT only verifies that the token is valid, but does not stop unauthenticated users from hitting endpoints.. Authentication identifies the user, but permissions authorize access. Without IsAuthenticated, your view would allow anonymous users to reach the logic, which is a common security oversight.

    From lesson: Authentication in DRF — JWT

  120. What happens if the 'SECRET_KEY' used to sign a JWT is compromised?

    • Only refresh tokens are invalidated.
    • The server will automatically generate a new one.
    • Any attacker can forge valid tokens for any user in the system.
    • The database records are automatically deleted.

    Answer: Any attacker can forge valid tokens for any user in the system.. The SECRET_KEY is the foundation of the signature. If compromised, an attacker can sign their own tokens and impersonate any user. It does not trigger automatic deletion or rotation.

    From lesson: Authentication in DRF — JWT

  121. When using PageNumberPagination, what is the primary benefit of using a custom pagination class over a simple list-based response?

    • It automatically caches all database queries to prevent duplicates.
    • It provides structured metadata like total count, page links, and next/previous pointers.
    • It forces the client to download the entire database table at once.
    • It bypasses the need for serializers by returning raw database objects.

    Answer: It provides structured metadata like total count, page links, and next/previous pointers.. The pagination class wraps results in a response containing metadata needed by clients for navigation. Option 0 is wrong as caching is handled elsewhere; 2 is wrong because pagination prevents full downloads; 3 is wrong because serializers are still required for the result list.

    From lesson: Filtering and Pagination in DRF

  122. If you want to filter a list of products by category using the URL query parameter ?category=books, what is the most efficient DRF approach?

    • Manually iterate through all items in the queryset within the list method.
    • Use a FilterSet class with DjangoFilterBackend to map the query parameter to a database field.
    • Convert the entire queryset to a list and filter using Python's list comprehension.
    • Write a custom middleware to intercept the request and slice the queryset.

    Answer: Use a FilterSet class with DjangoFilterBackend to map the query parameter to a database field.. Using DjangoFilterBackend is the standard, optimized DRF way to handle queries. Manual iteration (0) and list comprehension (2) are extremely slow for large datasets. Middleware (3) is not the correct architectural layer for filtering business data.

    From lesson: Filtering and Pagination in DRF

  123. Why should you use 'filterset_fields' in a ReadOnlyModelViewSet instead of overriding 'get_queryset'?

    • Overriding get_queryset is impossible in ViewSets.
    • filterset_fields automatically generates an interface for the browsable API and handles complex filtering logic securely.
    • get_queryset does not support filtering by foreign keys.
    • It is required by the Django ORM for all query operations.

    Answer: filterset_fields automatically generates an interface for the browsable API and handles complex filtering logic securely.. Declarative filter fields provide automation and better security/validation. Overriding get_queryset is possible (0), but manually coding filters is error-prone. 2 and 3 are factually incorrect regarding ORM capabilities.

    From lesson: Filtering and Pagination in DRF

  124. What happens if a client requests page 50 but the dataset only has 10 pages using PageNumberPagination?

    • The server returns a 404 Not Found error.
    • The server crashes and returns a 500 Internal Server Error.
    • The server returns the first page instead.
    • The server returns an empty results list for that page.

    Answer: The server returns a 404 Not Found error.. DRF's default behavior is to raise an EmptyPage exception, which results in a 404 response. It does not crash (1), loop back to the first page (2), or show empty results (3) by default.

    From lesson: Filtering and Pagination in DRF

  125. How does setting 'max_page_size' in a pagination class protect your server?

    • It prevents clients from requesting a huge number of objects in a single query, which would cause memory exhaustion.
    • It limits the number of database connections to the server.
    • It prevents unauthorized users from accessing the API.
    • It restricts the number of times a user can make a request per minute.

    Answer: It prevents clients from requesting a huge number of objects in a single query, which would cause memory exhaustion.. Large page sizes can lead to excessive memory consumption. Limiting this prevents denial-of-service style requests. 1 refers to DB pooling, 2 to authentication/permission, and 3 to rate limiting.

    From lesson: Filtering and Pagination in DRF

  126. When should you prefer a pre_save signal over a post_save signal for modifying a model instance field?

    • When you need the primary key of the object to be already assigned by the database.
    • When you want to avoid an extra database hit to save the instance again.
    • When you need to trigger a notification to an external email service.
    • When you want to ensure the object has already been committed to the database.

    Answer: When you want to avoid an extra database hit to save the instance again.. In pre_save, the instance has not yet been written to the DB, so modifying fields does not require an extra save() call. The other options are incorrect because pre_save does not guarantee a primary key (if not set) and is not suitable for external side effects that should only occur after a successful database commit.

    From lesson: Signals — pre_save, post_save

  127. What is the primary risk of calling instance.save() inside a post_save signal without any guards?

    • It will raise a DatabaseError because the transaction is already closed.
    • It will cause a Circular Dependency error during Django startup.
    • It will cause an infinite recursion loop, crashing the application.
    • It will ignore the changes because the signal is read-only.

    Answer: It will cause an infinite recursion loop, crashing the application.. Calling save() triggers the post_save signal again, which then calls save() again, leading to an infinite recursion. Options 1 and 4 are incorrect because the transaction remains open and the save() method is not read-only.

    From lesson: Signals — pre_save, post_save

  128. How does Django's bulk_create method interact with signals?

    • It triggers post_save for every object created in the list.
    • It triggers both pre_save and post_save for each object.
    • It triggers a single bulk_post_save signal for the whole operation.
    • It ignores pre_save and post_save signals entirely.

    Answer: It ignores pre_save and post_save signals entirely.. Bulk operations in Django are designed for performance and explicitly bypass model-level signals. Options 1, 2, and 3 are incorrect as Django does not emit these signals for bulk database operations.

    From lesson: Signals — pre_save, post_save

  129. Which of the following scenarios is best suited for a post_save signal?

    • Setting a default value for a field based on another field in the same object.
    • Hashing a password before it hits the database.
    • Updating a profile statistics model count after a user is created.
    • Validating data integrity before it enters the database.

    Answer: Updating a profile statistics model count after a user is created.. post_save is ideal for maintaining related data or cross-model dependencies that require the primary instance to exist. Pre_save is better for data cleaning (options 1, 2, and 4) to ensure data is sanitized before it reaches the database.

    From lesson: Signals — pre_save, post_save

  130. Why is it important to use 'update_fields' when calling save() inside a signal?

    • It prevents the signals from firing indefinitely.
    • It ensures that only specific columns are updated, reducing database load.
    • It automatically commits the transaction to the database.
    • It bypasses validation logic in the model's clean method.

    Answer: It ensures that only specific columns are updated, reducing database load.. Using update_fields limits the database query to only the necessary columns, improving performance. It does not stop signals (as save() will still fire) or bypass clean methods; it is purely an optimization for SQL updates.

    From lesson: Signals — pre_save, post_save

  131. Which of the following is the most efficient approach to cache a expensive queryset in a Django view?

    • Store the raw QuerySet object directly in the cache.
    • Serialize the QuerySet result to a list and store that list in the cache.
    • Re-query the database every time to ensure data freshness.
    • Store the entire HTML template string after rendering the view.

    Answer: Serialize the QuerySet result to a list and store that list in the cache.. Option 1 is correct because QuerySets are lazy and not inherently serializable by standard cache backends. Option 0 fails because the QuerySet object itself cannot be pickled. Option 2 defeats the purpose of caching. Option 3 is an anti-pattern known as fragment caching that is often overkill for simple data lookups.

    From lesson: Caching with Redis

  132. If you are using Django's per-view caching, how does it determine if the cache is valid for a given request?

    • It only considers the URL path.
    • It considers the URL path, the GET/POST parameters, and the language header.
    • It only checks if the user is authenticated.
    • It checks the current system time against the template modification time.

    Answer: It considers the URL path, the GET/POST parameters, and the language header.. Option 1 is correct because the cache key must be unique per request variation to prevent serving the wrong data. Option 0 is too simplistic. Option 2 is irrelevant to request-level caching. Option 3 is incorrect as template modification time is managed by the template loader, not the cache middleware.

    From lesson: Caching with Redis

  133. Why is it recommended to use a unique prefix for your Redis cache keys in a Django settings file?

    • To speed up the connection handshake.
    • To ensure different Django projects on the same Redis instance do not overwrite each other's data.
    • To allow Redis to store keys in different physical partitions.
    • To encrypt the data stored in the cache.

    Answer: To ensure different Django projects on the same Redis instance do not overwrite each other's data.. Option 1 is correct because namespaces prevent key collisions in shared environments. Options 0 and 2 are technically incorrect regarding how Redis manages keys. Option 3 is false as caching is not for encryption purposes.

    From lesson: Caching with Redis

  134. What happens if the cache timeout is set to None in a Django cache.set() call?

    • The item is immediately evicted.
    • The item is cached until the Redis instance is restarted or the key is manually deleted.
    • Django throws a TypeError.
    • The item is cached for a default period of 300 seconds.

    Answer: The item is cached until the Redis instance is restarted or the key is manually deleted.. Option 1 is correct because None indicates that the key should never expire automatically. Option 0 describes a failure, not a default behavior. Option 2 is incorrect as the method supports None. Option 3 is incorrect because the default timeout is defined in settings, but explicitly passing None overrides this to signify 'never expire'.

    From lesson: Caching with Redis

  135. When using the @cache_page decorator on a Django view, what is the best way to invalidate the cache manually?

    • Delete the specific cache key using cache.delete().
    • Clear the entire Redis database.
    • Modify the view code to force an update.
    • Update the database record that the view relies on.

    Answer: Delete the specific cache key using cache.delete().. Option 0 is correct because targeted deletion allows you to refresh specific content without affecting the rest of the application. Option 1 is too destructive. Option 2 is not a programmatic invalidation strategy. Option 3 is ineffective because the cache persists even after the database record changes unless the cache key logic is explicitly coupled to the data change.

    From lesson: Caching with Redis

  136. When a Django view triggers a background task, why is it recommended to pass only the ID of a database object rather than the object instance itself?

    • To save memory on the broker by sending smaller payloads
    • To ensure the task works on data that matches the database state at the time of execution
    • To bypass Django's default serialization limitations
    • To prevent the worker from needing a connection to the database

    Answer: To ensure the task works on data that matches the database state at the time of execution. Passing an ID ensures that the task fetches fresh data from the database when it runs, preventing issues caused by stale data or race conditions. Option 0 is minor; Option 2 is incorrect as Django handles model serialization; Option 3 is wrong because the worker needs the DB to perform operations on the object.

    From lesson: Celery with Django

  137. What is the primary purpose of using 'transaction.on_commit' when calling a Celery task inside a Django view?

    • To speed up the execution time of the background task
    • To allow the Celery worker to perform database transactions
    • To delay task triggering until the database transaction has successfully committed
    • To ensure that the task runs in the same thread as the web request

    Answer: To delay task triggering until the database transaction has successfully committed. Transactions are isolated, so if a task triggers before the commit, it might look for data that doesn't exist yet. 'on_commit' prevents this race condition. Options 0, 1, and 3 misidentify the role of transaction management in distributed task execution.

    From lesson: Celery with Django

  138. Which of the following describes the behavior of a Celery worker when the result backend is not configured in Django?

    • The worker will fail to start
    • The task will execute successfully, but the result cannot be retrieved by the application
    • The task will execute, but its status will always be 'PENDING'
    • The broker will store the results automatically

    Answer: The task will execute successfully, but the result cannot be retrieved by the application. Celery executes the task logic regardless of the result backend. However, without a backend, the application loses the ability to query task results. Options 0, 2, and 3 are technically incorrect as the worker runs fine and the broker handles messages, not result persistence.

    From lesson: Celery with Django

  139. If you have a task that needs to run periodically, which Django-Celery integration component is typically used?

    • Celery Beat
    • Celery Flower
    • Django Celery Results
    • The Django middleware component

    Answer: Celery Beat. Celery Beat is the scheduler responsible for triggering tasks at specified intervals. Flower is for monitoring, Results stores output, and middleware is for request processing, making them incorrect for scheduling.

    From lesson: Celery with Django

  140. Why is it generally discouraged to perform database queries directly in the task signature definition rather than inside the task function body?

    • Because task signatures are calculated every time the broker checks for tasks
    • Because queries inside the definition execute at the time of task dispatch, not task execution
    • Because it violates the DRY principle of Django
    • Because Celery signatures do not support ORM methods

    Answer: Because queries inside the definition execute at the time of task dispatch, not task execution. Code inside the call/signature definition runs when the task is sent to the queue. Moving it inside the function body ensures logic runs during worker processing. Other options are irrelevant to the timing issue of task dispatch.

    From lesson: Celery with Django

  141. What is the primary benefit of using select_related() in a Django QuerySet?

    • It caches the entire database table in memory to speed up lookups.
    • It performs an SQL JOIN to retrieve related objects in a single query.
    • It triggers a separate database hit for every row processed in a loop.
    • It prevents the database from creating indexes on foreign key fields.

    Answer: It performs an SQL JOIN to retrieve related objects in a single query.. select_related() uses a SQL JOIN to fetch foreign key data at once, avoiding the N+1 query problem. Option 0 is false as Django does not cache full tables. Option 2 describes the default behavior without optimization. Option 3 is unrelated to indexing.

    From lesson: Django Interview Questions

  142. When should you use a QuerySet's .annotate() method instead of .aggregate()?

    • When you need a single result value for the entire table.
    • When you need to modify the structure of the database schema.
    • When you need to perform calculations on each individual object in the queryset.
    • When you are writing raw SQL queries manually.

    Answer: When you need to perform calculations on each individual object in the queryset.. .annotate() adds a calculated field to every object in a queryset, whereas .aggregate() produces a single dictionary result for the whole set. Option 1 describes aggregate. Option 3 is incorrect because annotate is ORM-based.

    From lesson: Django Interview Questions

  143. Why is it discouraged to perform database queries inside a template?

    • Templates do not support Python syntax.
    • It violates the separation of concerns and leads to slow, unpredictable page loads.
    • Django templates automatically raise an exception if a query is detected.
    • It forces the use of raw SQL rather than ORM.

    Answer: It violates the separation of concerns and leads to slow, unpredictable page loads.. Logic and database access belong in the View. Doing this in templates creates performance bottlenecks (like N+1 queries) and violates the MVC/MVT pattern. Options 0, 2, and 3 are technically incorrect statements about Django template functionality.

    From lesson: Django Interview Questions

  144. What happens when you call .save() on a Django Model instance that already exists in the database?

    • Django throws an IntegrityError automatically.
    • It creates a new row with the same primary key.
    • It performs an SQL UPDATE query based on the primary key.
    • It ignores the call entirely and does nothing.

    Answer: It performs an SQL UPDATE query based on the primary key.. Django's save() method is an 'upsert'. If the primary key is set and found, it updates the existing record. It does not crash with an error, nor does it create a duplicate. It definitely does not ignore the request.

    From lesson: Django Interview Questions

  145. How does Django ensure that a form submitted via a POST request is legitimate?

    • By checking the user's IP address against the database.
    • By requiring a hidden CSRF token included in the form data.
    • By verifying that the request came from a secure HTTPS browser.
    • By validating that the user is logged in as a superuser.

    Answer: By requiring a hidden CSRF token included in the form data.. The CSRF middleware requires a hidden field generated by the server. This prevents attackers from submitting forms on behalf of the user. The other options are either not related to security tokens or are incorrect methods of verification.

    From lesson: Django Interview Questions

  146. Which scenario most strongly dictates the selection of Django over FastAPI?

    • The project requires a high-concurrency microservice with no persistent storage.
    • The project requires a comprehensive Admin dashboard and user authentication system out of the box.
    • The project requires sub-millisecond serialization for simple JSON payloads.
    • The project needs to avoid all built-in database ORMs.

    Answer: The project requires a comprehensive Admin dashboard and user authentication system out of the box.. Django's Admin and Auth modules provide instant functional value. Option 0 and 2 favor lightweight frameworks, and Option 3 is a misinterpretation of Django's capability.

    From lesson: Django vs FastAPI — When to Use Which

  147. When building a web application, how does Django's 'batteries-included' philosophy impact the development cycle compared to FastAPI?

    • It forces the developer to write more boilerplate code for database migrations.
    • It provides standard tools for form validation, security, and ORM, reducing the need for external integrations.
    • It prevents the use of asynchronous programming entirely.
    • It creates slower execution speeds because it includes unnecessary features.

    Answer: It provides standard tools for form validation, security, and ORM, reducing the need for external integrations.. Django provides an integrated ecosystem. Option 0 is false as migrations are automated; Option 2 is false due to modern ASGI support; Option 3 is incorrect as feature richness does not inherently equal slow execution.

    From lesson: Django vs FastAPI — When to Use Which

  148. A team is worried about security implementation in their new project. Why is Django often preferred for enterprise security?

    • It runs on a faster, non-standard web server by default.
    • It enforces a specific directory structure that is harder to hack.
    • It includes built-in protection against SQL injection, CSRF, and clickjacking.
    • It requires less configuration for external libraries.

    Answer: It includes built-in protection against SQL injection, CSRF, and clickjacking.. Django's security middleware is a core feature. The other options refer to architectural patterns or false assumptions about security implementations.

    From lesson: Django vs FastAPI — When to Use Which

  149. How should a developer view the 'async' capabilities of Django in a modern project?

    • Django is purely synchronous and cannot handle long-running background tasks.
    • Django has evolved to support asynchronous views and middleware, allowing it to compete with high-concurrency needs.
    • Async in Django is strictly limited to template rendering only.
    • Django forces every request to be synchronous, regardless of configuration.

    Answer: Django has evolved to support asynchronous views and middleware, allowing it to compete with high-concurrency needs.. Django's ASGI support makes it a capable async framework. The other options underestimate Django's modern architectural improvements.

    From lesson: Django vs FastAPI — When to Use Which

  150. In the context of database management, why is the Django ORM considered a primary advantage for complex data applications?

    • It automatically translates every query into raw machine code.
    • It allows developers to define data models in Python, abstracting complex database interactions and migrations.
    • It is the only way to connect to a SQL database in Python.
    • It forces developers to write all queries in standard SQL, preventing abstraction errors.

    Answer: It allows developers to define data models in Python, abstracting complex database interactions and migrations.. The Django ORM is a powerful abstraction layer. Option 0 and 3 are technically inaccurate, and Option 2 describes a non-existent requirement.

    From lesson: Django vs FastAPI — When to Use Which