Django Django Views & URLs 2 — Questions and Answers
Question 1: What is the purpose of `include()` in Django's URL configuration?
- To include URL patterns from another module, enabling URL namespacing (Correct answer)
- To include static files in URLs
- To merge two URL lists together
- To add middleware to specific URL paths
Correct answer: To include URL patterns from another module, enabling URL namespacing
include() lets you reference another URLconf module, allowing URL patterns to be split across multiple apps for better organization.
Question 2: Which Django generic CBV is used to display a list of objects?
- ListView (Correct answer)
- DetailView
- TemplateView
- ObjectView
Correct answer: ListView
ListView inherits from MultipleObjectMixin and renders a template with a queryset of model objects via object_list.
Question 3: What does `get_object_or_404()` do in a Django view?
- Fetches an object or returns a 404 response if not found (Correct answer)
- Fetches an object or creates it if not found
- Filters objects and returns 404 on empty sets
- Returns None instead of raising DoesNotExist
Correct answer: Fetches an object or returns a 404 response if not found
get_object_or_404() calls get() on the model manager and raises Http404 instead of DoesNotExist when the object is not found.
Question 4: What is the `request.POST` object in Django?
- A QueryDict containing data from a POST request body (Correct answer)
- A dict of URL query parameters
- A list of uploaded files
- The parsed JSON body of a request
Correct answer: A QueryDict containing data from a POST request body
request.POST is a QueryDict that provides access to form data submitted via an HTTP POST request with application/x-www-form-urlencoded encoding.
Question 5: Which CBV mixin is used to restrict a class-based view to authenticated users?
- LoginRequiredMixin (Correct answer)
- AuthRequiredMixin
- PermissionMixin
- SecureMixin
Correct answer: LoginRequiredMixin
LoginRequiredMixin is the CBV equivalent of @login_required and should be listed first in the class's inheritance to ensure the check runs first.
Question 6: What does the `as_view()` method do on a Django class-based view?
- Converts the CBV class into a callable that Django's URL router can use (Correct answer)
- Renders the view's template as a string
- Returns a ViewSet for REST APIs
- Registers the CBV with the admin site
Correct answer: Converts the CBV class into a callable that Django's URL router can use
as_view() is a class method that returns a view function wrapping the class instance, which is what Django's URL configuration expects.
What is the purpose of `include()` in Django's URL configuration?