W3Schools Django Certification Exam — Questions and Answers
Question 1: Which Django permission method checks if a user has a specific model-level permission?
- user.can('app.codename')
- user.is_permitted('app.codename')
- user.check_perm('app.codename')
- user.has_perm('app.codename') (Correct answer)
Correct answer: user.has_perm('app.codename')
has_perm() checks if the user has the given permission via the authentication backends and returns True or False.
Question 2: How do you capture a URL parameter as an integer in Django's path() routing?
- <int:pk> (Correct answer)
- [int:pk]
- (int:pk)
- {int:pk}
Correct answer: <int:pk>
Angle brackets with a type converter like <int:pk> capture and automatically convert the URL segment to a Python integer.
Question 3: When using `self.assertContains(response, 'text', count=2)`, what does the `count` parameter do?
- Asserts at least 2 bytes were returned
- Asserts the text appears exactly 2 times in the response (Correct answer)
- Asserts the response was returned in under 2 seconds
- Asserts the status code is 200 twice
Correct answer: Asserts the text appears exactly 2 times in the response
The count parameter in assertContains verifies that the text appears exactly that many times in the response content.
Question 4: How does Django's template inheritance handle content in a child template outside of blocks?
- It appends it to the parent template's body
- It ignores all content outside block tags in child templates (Correct answer)
- It raises a TemplateSyntaxError
- It renders it before the parent template
Correct answer: It ignores all content outside block tags in child templates
When using template inheritance with {% extends %}, only content inside {% block %} tags is rendered; everything else in the child template is silently ignored.
Question 5: In a Django form, what does is_valid() do?
- Render the form HTML
- Save the form to the database
- Run validation and populate cleaned_data (Correct answer)
- Reset the form fields
Correct answer: Run validation and populate cleaned_data
is_valid() validates submitted data and fills cleaned_data when validation passes.
Question 6: What does `serializer.is_valid(raise_exception=True)` do in DRF?
- Skips validation and saves directly
- Validates and saves the data in one step
- Validates the serializer data and automatically returns a 400 response if invalid (Correct answer)
- Raises a Python exception that crashes the server
Correct answer: Validates the serializer data and automatically returns a 400 response if invalid
With raise_exception=True, DRF automatically returns a 400 Bad Request response with validation errors instead of requiring manual error handling.
Question 7: What function reverses a URL pattern by name in Django?
- reverse() (Correct answer)
- geturl()
- resolve()
- url()
Correct answer: reverse()
reverse() takes a URL name and optional arguments to generate the corresponding URL string, avoiding hardcoded URLs.
Question 8: What does DRF's `@action` decorator do on a ViewSet method?
- Marks a method as asynchronous
- Adds authentication to a single ViewSet method
- Creates a custom endpoint on the ViewSet beyond the standard CRUD actions (Correct answer)
- Caches the result of the ViewSet method
Correct answer: Creates a custom endpoint on the ViewSet beyond the standard CRUD actions
The @action decorator defines additional routes on a ViewSet, specifying detail=True for object-level actions or False for collection-level actions.
Question 9: What does `{{ forloop.counter }}` provide inside a Django for loop?
- The 0-based index of the current loop iteration
- The total number of items in the loop
- The 1-based index of the current loop iteration (Correct answer)
- A boolean indicating the last iteration
Correct answer: The 1-based index of the current loop iteration
forloop.counter gives the current iteration number starting at 1; use forloop.counter0 for a 0-based index.
Question 10: Which ORM method returns a QuerySet of all objects matching a condition without raising exceptions?
- search()
- filter() (Correct answer)
- fetch()
- get()
Correct answer: filter()
filter() returns a QuerySet containing all objects that match the given lookup parameters, returning an empty QuerySet if none are found.
Question 11: What does `form.as_p()` do in Django?
- Renders the form fields wrapped in HTML <p> tags (Correct answer)
- Renders the form as a paragraph of text
- Outputs the form's action URL
- Converts the form to a PDF
Correct answer: Renders the form fields wrapped in HTML <p> tags
as_p() is a convenience method that renders all form fields and labels wrapped in <p> elements, providing quick HTML output.
Question 12: What is the purpose of Django's `AUTH_PASSWORD_VALIDATORS` setting?
- Sets the hashing algorithm for passwords
- Controls the session timeout duration
- Defines rules like minimum length and common password checks enforced on password changes (Correct answer)
- Specifies allowed characters in usernames
Correct answer: Defines rules like minimum length and common password checks enforced on password changes
AUTH_PASSWORD_VALIDATORS is a list of validator classes that run when users set or change passwords, enforcing strength requirements.
Question 13: Which DRF authentication class validates API requests using a token in the Authorization header?
- TokenAuthentication (Correct answer)
- SessionAuthentication
- JWTAuthentication
- BasicAuthentication
Correct answer: TokenAuthentication
TokenAuthentication expects an 'Authorization: Token <key>' header and validates it against tokens stored in the authtoken_token database table.
Question 14: What is the purpose of DRF's `permission_classes` on a view?
- To restrict access to the API endpoint based on user authentication or permissions (Correct answer)
- To enable rate limiting on the endpoint
- To set the response format (JSON/XML)
- To define which HTTP methods the endpoint accepts
Correct answer: To restrict access to the API endpoint based on user authentication or permissions
permission_classes is a list of permission check classes that run before the view handler, returning 403 if any check fails.
Question 15: What is the `{% csrf_token %}` tag used for in Django forms?
- Encrypts form data before submission
- Validates form input on the client side
- Generates a nonce for Content Security Policy
- Inserts a hidden CSRF token field to protect against cross-site request forgery (Correct answer)
Correct answer: Inserts a hidden CSRF token field to protect against cross-site request forgery
{% csrf_token %} renders a hidden input field with a CSRF token that Django's middleware validates on POST requests to prevent CSRF attacks.
Question 16: Which Django setting enables automatic escaping of template variables to prevent XSS?
- Django auto-escapes by default; no setting is needed to enable it (Correct answer)
- SECURITY_ESCAPE = True
- TEMPLATE_AUTO_ESCAPE = True
- XSS_PROTECTION = True
Correct answer: Django auto-escapes by default; no setting is needed to enable it
Django's template engine auto-escapes all variable output by default, converting dangerous characters to HTML entities without any configuration.
Question 17: What does Django's F() expression let you do?
- Define a form field
- Reference a model field's value in a database query (Correct answer)
- Format a string in templates
- Filter by foreign keys
Correct answer: Reference a model field's value in a database query
F() references field values at the database level, enabling atomic updates and field comparisons.
Question 18: What does Django's atomic() context manager guarantee for a block of database operations?
- All succeed together or none are committed (Correct answer)
- Queries are cached
- Operations run in parallel
- Migrations are skipped
Correct answer: All succeed together or none are committed
transaction.atomic() wraps operations so they commit as a unit or roll back on error.
Question 19: Which Django view class is best for displaying and processing a single model's create form?
- CreateView (Correct answer)
- FormView
- UpdateView
- DetailView
Correct answer: CreateView
CreateView provides built-in form rendering, validation, and object creation for a model, requiring only model, fields, and success_url.
Question 20: Which HttpResponse subclass performs a permanent redirect in Django?
- HttpResponseRedirect
- HttpResponsePermanentRedirect (Correct answer)
- HttpResponseMovedPermanently
- HttpResponseForward
Correct answer: HttpResponsePermanentRedirect
HttpResponsePermanentRedirect returns a 301 status code, while HttpResponseRedirect returns a 302 temporary redirect.
Question 21: Which Django template tag is used for conditional rendering?
- {% if condition %}...{% endif %} (Correct answer)
- {% check condition %}...{% done %}
- {% cond condition %}...{% endcond %}
- {% when condition %}...{% end %}
Correct answer: {% if condition %}...{% endif %}
The {% if %} tag evaluates a condition and renders its contents only when the condition is truthy; it supports {% elif %} and {% else %} branches.
Question 22: What does Django's CSRF middleware protect against?
- SQL injection via form inputs
- Cross-Site Scripting via template variables
- Brute-force login attacks
- Cross-Site Request Forgery attacks where malicious sites submit requests on behalf of authenticated users (Correct answer)
Correct answer: Cross-Site Request Forgery attacks where malicious sites submit requests on behalf of authenticated users
CSRF middleware validates a secret token in POST/PUT/DELETE requests to ensure they originate from the same site, not a malicious third-party page.
Question 23: What does the `kwargs` parameter in a Django URL pattern represent?
- Session variables
- Additional keyword arguments passed to the view from the URL configuration (Correct answer)
- Query string parameters
- HTTP headers from the request
Correct answer: Additional keyword arguments passed to the view from the URL configuration
URL patterns can pass extra keyword arguments to views using the third argument in path(), allowing contextual data beyond URL captures.
Question 24: How do you define a URL namespace in Django to avoid name collisions between apps?
- Set NAMESPACE in settings.py
- Set app_name in the app's urls.py or use namespace= in include() (Correct answer)
- Use unique URL names across all apps
- Use the @namespace decorator on views
Correct answer: Set app_name in the app's urls.py or use namespace= in include()
Defining app_name = 'myapp' in urls.py or passing namespace='myapp' to include() allows you to reference URLs as 'myapp:viewname'.
Question 25: What is the difference between a function-based view (FBV) and a class-based view (CBV) in Django?
- FBVs support only GET; CBVs support all methods
- FBVs are plain functions; CBVs are classes that inherit from Django view classes (Correct answer)
- FBVs are deprecated in Django 4+
- FBVs are faster; CBVs are slower
Correct answer: FBVs are plain functions; CBVs are classes that inherit from Django view classes
FBVs are Python functions taking a request and returning a response, while CBVs are classes that provide built-in mixins and method dispatch for HTTP verbs.
Question 26: What does `get_object_or_404()` do in a Django view?
- Fetches an object or returns a 404 response if not found (Correct answer)
- Filters objects and returns 404 on empty sets
- Returns None instead of raising DoesNotExist
- Fetches an object or creates it if not found
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 27: What does marking a variable with `{{ value|safe }}` do in Django templates?
- Converts the value to a safe string type
- Validates the value against XSS patterns
- Marks the value as safe for database storage
- Disables auto-escaping for that variable, rendering raw HTML (Correct answer)
Correct answer: Disables auto-escaping for that variable, rendering raw HTML
The safe filter tells Django's template engine to trust the variable's content and render it as raw HTML without escaping, which should only be used with trusted data.
Question 28: What does Django's `check_password(raw_password, encoded)` function do?
- Hashes a new password for storage
- Checks if a password has been compromised
- Validates password strength against AUTH_PASSWORD_VALIDATORS
- Verifies a plaintext password against a stored hashed password (Correct answer)
Correct answer: Verifies a plaintext password against a stored hashed password
check_password() hashes the raw password using the same algorithm identified in the encoded hash and compares them securely using a constant-time comparison.
Question 29: What is Django's `AbstractUser` model used for?
- Creating users without database tables
- Building API token-based authentication
- Extending the built-in User model with additional fields while keeping all default auth features (Correct answer)
- Defining permission groups
Correct answer: Extending the built-in User model with additional fields while keeping all default auth features
AbstractUser allows you to add custom fields to Django's built-in user model by subclassing it, which is the recommended approach for custom user models.
Question 30: Which setting must be set to use a custom user model in Django?
- AUTH_USER_MODEL (Correct answer)
- DEFAULT_USER_MODEL
- CUSTOM_USER_MODEL
- USER_MODEL
Correct answer: AUTH_USER_MODEL
AUTH_USER_MODEL = 'myapp.CustomUser' must be set before the first migration to tell Django which model to use for authentication.
Question 31: What does `{{ value|truncatewords:10 }}` do in a Django template?
- Splits the string into a 10-word list
- Removes the last 10 words
- Truncates the string to 10 words and appends an ellipsis (Correct answer)
- Limits the string to 10 characters
Correct answer: Truncates the string to 10 words and appends an ellipsis
The truncatewords filter cuts off the string after the given number of words and appends '...' to indicate truncation.
Question 32: What features does the Django web framework have?
- All of the above (Correct answer)
- Admin Interface
- Form handling
- Templating
Correct answer: All of the above
Django is known for being a 'batteries-included' framework, offering a comprehensive set of features out-of-the-box. This includes a powerful templating system for rendering dynamic HTML, an automatic and highly customizable admin interface for managing data, and robust form handling capabilities for processing user input. These features collectively streamline web development.
Question 33: What is the Django `DEBUG` setting typically set to in the test environment?
- True, so error details are visible
- Depends on the DJANGO_ENV variable
- None, to disable error pages
- False, to match production behavior (Correct answer)
Correct answer: False, to match production behavior
Django's test runner sets DEBUG=False by default so tests run in an environment closer to production, revealing issues hidden by debug mode.
Question 34: Which template tag is used to extend a base template in Django?
- {% extends 'base.html' %} (Correct answer)
- {% inherit 'base.html' %}
- {% include 'base.html' %}
- {% parent 'base.html' %}
Correct answer: {% extends 'base.html' %}
{% extends %} must be the first tag in a child template and tells Django to use the named template as the parent layout.
Question 35: Which setting controls whether detailed error pages are shown to users?
- DEBUG (Correct answer)
- INSTALLED_APPS
- ALLOWED_HOSTS
- SECRET_KEY
Correct answer: DEBUG
DEBUG should be False in production to avoid leaking sensitive error details.
Question 36: What does the `as_view()` method do on a Django class-based view?
- Returns a ViewSet for REST APIs
- Renders the view's template as a string
- Registers the CBV with the admin site
- Converts the CBV class into a callable that Django's URL router can use (Correct answer)
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.
Question 37: What does DRF's `HyperlinkedModelSerializer` add compared to `ModelSerializer`?
- Uses URLs instead of primary keys for relationships between resources (Correct answer)
- Generates clickable HTML links in the browsable API
- Adds HATEOAS hypermedia links to all response fields
- Compresses responses using HTTP link compression
Correct answer: Uses URLs instead of primary keys for relationships between resources
HyperlinkedModelSerializer uses a url field and HyperlinkedRelatedField for relationships, returning full URLs instead of IDs for related objects.
Question 38: How do you raise a validation error in a Django form's clean method?
- raise ValueError('message')
- return forms.Invalid('message')
- raise forms.ValidationError('message') (Correct answer)
- return None
Correct answer: raise forms.ValidationError('message')
Raising forms.ValidationError inside any clean method signals Django to mark the form as invalid and add the error to the field or non-field errors.
Question 39: What is a DRF Serializer used for?
- Defining URL routes for API endpoints
- Caching API responses
- Handling authentication tokens
- Converting model instances to Python native types (and back) for API input/output (Correct answer)
Correct answer: Converting model instances to Python native types (and back) for API input/output
Serializers handle data conversion between complex types like Django models and JSON-compatible Python primitives, including validation on input.
Question 40: Which DRF pagination class splits results into pages of a fixed size?
- CursorPagination
- LimitOffsetPagination
- PageNumberPagination (Correct answer)
- FixedPagination
Correct answer: PageNumberPagination
PageNumberPagination splits querysets into pages accessed via a page query parameter, configurable with PAGE_SIZE in DEFAULT_PAGINATION_CLASS settings.
Question 41: How does DRF's `ModelSerializer` handle the `create()` method by default?
- It raises NotImplementedError requiring manual implementation
- It calls Model.objects.create() with the validated data (Correct answer)
- It calls the model's __init__ and then save()
- It uses Django's form save() method
Correct answer: It calls Model.objects.create() with the validated data
ModelSerializer's default create() calls Model.objects.create(**validated_data), which creates and saves the instance in one database operation.
Question 42: Which template tag iterates over a list in Django?
- {% iterate item in list %}
- {% each item in list %}
- {% loop item in list %}
- {% for item in list %} (Correct answer)
Correct answer: {% for item in list %}
The {% for %} tag loops over each item in a sequence and must be closed with {% endfor %}.
Question 43: What is the purpose of a form's `clean()` method?
- To perform cross-field validation after individual field cleaning (Correct answer)
- To sanitize SQL injection in form data
- To reset all field values to their defaults
- To apply CSS classes to form fields
Correct answer: To perform cross-field validation after individual field cleaning
The form-level clean() method runs after all individual field clean methods and is used to validate relationships between multiple fields.
Question 44: What does `login(request, user)` do in Django?
- Attaches the user to the session and marks them as logged in (Correct answer)
- Verifies the user's credentials
- Generates an authentication token
- Creates a new user account
Correct answer: Attaches the user to the session and marks them as logged in
login() saves the user's ID to the session using Django's session framework, establishing the logged-in state across requests.
Question 45: What HTTP status code does Django's `Http404` exception result in?
- 403
- 400
- 404 (Correct answer)
- 500
Correct answer: 404
Raising Http404 causes Django to return a 404 Not Found response, optionally rendering a custom 404.html template.
Question 46: Which Django generic CBV is used to display a list of objects?
- ObjectView
- TemplateView
- DetailView
- ListView (Correct answer)
Correct answer: ListView
ListView inherits from MultipleObjectMixin and renders a template with a queryset of model objects via object_list.
Question 47: What syntax is used to output a variable in a Django template?
- {% variable %}
- <% variable %>
- {{ variable }} (Correct answer)
- ${variable}
Correct answer: {{ variable }}
Double curly braces {{ }} are the Django template tag for rendering variable values; single curly-percent {% %} is used for block tags.
Question 48: Which template filter safely escapes HTML characters in Django?
- safe
- sanitize
- html_escape
- escape (Correct answer)
Correct answer: escape
The escape filter converts characters like <, >, &, and quotes to their HTML entity equivalents to prevent XSS; Django auto-escapes by default.
Question 49: What is the purpose of DRF's `SerializerMethodField`?
- Creates a dynamic field based on request parameters
- Defines a writable field backed by a Python method
- Serializes a model method's return value automatically
- Adds a read-only field computed by a custom method on the serializer (Correct answer)
Correct answer: Adds a read-only field computed by a custom method on the serializer
SerializerMethodField calls a get_<fieldname>() method on the serializer to compute the field's value, useful for derived or annotated data.
Question 50: Which decorator restricts a view to logged-in users only?
- @requires_login
- @auth_required
- @authenticated
- @login_required (Correct answer)
Correct answer: @login_required
@login_required redirects unauthenticated users to the login page and is imported from django.contrib.auth.decorators.
Question 51: Which setting lists the apps Django loads for a project?
- MIDDLEWARE
- TEMPLATES
- DATABASES
- INSTALLED_APPS (Correct answer)
Correct answer: INSTALLED_APPS
INSTALLED_APPS registers applications so their models, templates, and admin are recognized.
Question 52: What is the `request.POST` object in Django?
- A list of uploaded files
- A dict of URL query parameters
- A QueryDict containing data from a POST request body (Correct answer)
- 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 53: How do you load a custom template tag library in Django?
- {% import mytaglib %}
- {% use mytaglib %}
- {% include mytaglib %}
- {% load mytaglib %} (Correct answer)
Correct answer: {% load mytaglib %}
{% load %} at the top of a template loads a custom tag library from a templatetags directory, making its tags and filters available.
Question 54: Which queryset method counts rows efficiently in the database?
- size()
- len()
- total()
- count() (Correct answer)
Correct answer: count()
count() issues a SQL COUNT query rather than loading all objects into memory.
Question 55: What is a QuerySet in Django?
- A SQL query string
- A single database row
- A database connection object
- A lazy collection of database objects that can be filtered and chained (Correct answer)
Correct answer: A lazy collection of database objects that can be filtered and chained
A QuerySet represents a collection of database rows that can be filtered, ordered, and evaluated lazily when the data is actually needed.
Question 56: How do you apply a template filter to a variable in Django?
- {% filter value %}
- {{ filtername(value) }}
- {{ value|filtername }} (Correct answer)
- {{ value.filtername }}
Correct answer: {{ value|filtername }}
The pipe character | applies a template filter to a variable, e.g., {{ name|upper }} converts the name to uppercase.
Question 57: What does setting `required=False` on a Django form field do?
- Hides the field from the rendered form
- Makes the field optional so empty values pass validation (Correct answer)
- Removes the field from cleaned_data
- Disables server-side validation for the field
Correct answer: Makes the field optional so empty values pass validation
By default form fields require a non-empty value; required=False allows the field to be submitted empty without triggering a validation error.
Question 58: What is the purpose of `include()` in Django's URL configuration?
- To include static files in URLs
- To add middleware to specific URL paths
- To include URL patterns from another module, enabling URL namespacing (Correct answer)
- To merge two URL lists together
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 59: What does `logout(request)` do in Django?
- Redirects the user to the login page
- Clears the authenticated user from the session and flushes session data (Correct answer)
- Revokes all authentication tokens
- Deletes the user's account
Correct answer: Clears the authenticated user from the session and flushes session data
logout() removes the user's session data, ensuring they are fully logged out and protecting against session fixation attacks.
Question 60: What does `path()` do in Django's URL configuration?
- Generates absolute URLs
- Creates URL redirects
- Maps a URL pattern to a view function or class (Correct answer)
- Defines URL namespaces
Correct answer: Maps a URL pattern to a view function or class
path() is used in urls.py to associate a string-based URL pattern with a view, supporting type converters like <int:pk>.
W3Schools Django Certification Exam
The W3Schools Django certification exam tests knowledge of the Django web framework, covering models, views, templates, authentication, REST framework, and core Django concepts. It is a widely recognized online certification for Python/Django developers.
Exam Rules
- You can skip questions and return to them later
- Flag questions for review before submitting
- No feedback shown until you submit the entire exam
- Unanswered questions count as wrong — answer everything
- 10 pretest questions are mixed in and don't affect your score
- Timer auto-submits when time runs out
- Your progress is auto-saved every 30 seconds