W3Schools Django Certification Exam — Questions and Answers
Question 1: What is the purpose of Django's `AUTH_PASSWORD_VALIDATORS` setting?
- Controls the session timeout duration
- Defines rules like minimum length and common password checks enforced on password changes (Correct answer)
- Sets the hashing algorithm for passwords
- 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 2: What does Django's CSRF middleware protect against?
- Brute-force login attacks
- SQL injection via form inputs
- Cross-Site Request Forgery attacks where malicious sites submit requests on behalf of authenticated users (Correct answer)
- Cross-Site Scripting via template variables
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 3: 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 renders it before the parent template
- It ignores all content outside block tags in child templates (Correct answer)
- It raises a TemplateSyntaxError
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 4: Which Django setting enables automatic escaping of template variables to prevent XSS?
- XSS_PROTECTION = True
- SECURITY_ESCAPE = True
- Django auto-escapes by default; no setting is needed to enable it (Correct answer)
- TEMPLATE_AUTO_ESCAPE = 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 5: What does `serializer.save()` do in DRF?
- Commits the serializer's data to a cache
- Validates and stores data in the session
- Calls create() or update() depending on whether an instance was provided (Correct answer)
- Saves the serializer schema to a file
Correct answer: Calls create() or update() depending on whether an instance was provided
If the serializer was initialized with an instance=obj argument, save() calls update(); otherwise it calls create() on the validated data.
Question 6: What does `form.as_p()` do in Django?
- Renders the form as a paragraph of text
- Outputs the form's action URL
- Converts the form to a PDF
- Renders the form fields wrapped in HTML <p> tags (Correct answer)
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 7: What does the `kwargs` parameter in a Django URL pattern represent?
- Session variables
- Query string parameters
- HTTP headers from the request
- Additional keyword arguments passed to the view from the URL configuration (Correct answer)
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 8: Which HttpResponse subclass performs a permanent redirect in Django?
- HttpResponsePermanentRedirect (Correct answer)
- HttpResponseMovedPermanently
- HttpResponseForward
- HttpResponseRedirect
Correct answer: HttpResponsePermanentRedirect
HttpResponsePermanentRedirect returns a 301 status code, while HttpResponseRedirect returns a 302 temporary redirect.
Question 9: What does `{{ value|truncatewords:10 }}` do in a Django template?
- Limits the string to 10 characters
- Truncates the string to 10 words and appends an ellipsis (Correct answer)
- Removes the last 10 words
- Splits the string into a 10-word list
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 10: How do you set up test-specific settings in Django without modifying the main settings file?
- Use the @override_settings decorator (Correct answer)
- Use a conftest.py file
- Create a test_settings.env file
- Edit settings.py before each test
Correct answer: Use the @override_settings decorator
@override_settings temporarily changes Django settings for a single test or test class, restoring them afterwards.
Question 11: Which of the following can be a view response?
- HTML contents
- XML document
- 404 error
- All of the above (Correct answer)
Correct answer: All of the above
A Django view function is responsible for processing a web request and returning an HTTP response. This response can take various forms, including rendered HTML content, JSON or XML data, redirects, or HTTP error codes like a 404 Not Found. Django's `HttpResponse` class and its subclasses provide the flexibility to return any of these types of responses.
Question 12: What is Django's `AbstractUser` model used for?
- Creating users without database tables
- Building API token-based authentication
- Defining permission groups
- Extending the built-in User model with additional fields while keeping all default auth features (Correct answer)
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 13: What is the `{% csrf_token %}` tag used for in Django forms?
- Generates a nonce for Content Security Policy
- Inserts a hidden CSRF token field to protect against cross-site request forgery (Correct answer)
- Validates form input on the client side
- Encrypts form data before submission
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 14: What does `serializer.is_valid(raise_exception=True)` do in DRF?
- 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
- Skips validation and saves directly
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 15: 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 16: Which field type would you use to store a many-to-many relationship in a Django model?
- OneToOneField
- ManyToManyField (Correct answer)
- ForeignKey
- RelatedField
Correct answer: ManyToManyField
ManyToManyField creates a junction table in the database to store many-to-many relationships between two models.
Question 17: Which template filter safely escapes HTML characters in Django?
- html_escape
- sanitize
- safe
- 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 18: Which Django ORM method deletes all objects matching a QuerySet?
- QuerySet.delete() (Correct answer)
- QuerySet.destroy()
- QuerySet.remove()
- QuerySet.drop()
Correct answer: QuerySet.delete()
Calling delete() on a QuerySet removes all matching objects from the database in an efficient bulk DELETE SQL statement.
Question 19: What is the purpose of `include()` in Django's URL configuration?
- To include URL patterns from another module, enabling URL namespacing (Correct answer)
- To add middleware to specific URL paths
- To merge two URL lists together
- To include static files in URLs
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 20: Which Django setting controls password hashing algorithms?
- PASSWORD_HASHERS (Correct answer)
- AUTH_PASSWORD_HASHERS
- PASSWORD_HASH_ALGORITHM
- SECURITY_HASHERS
Correct answer: PASSWORD_HASHERS
PASSWORD_HASHERS is a list of hasher classes in priority order; Django uses the first one for new passwords and can upgrade older hashes automatically.
Question 21: What is Django middleware?
- A caching layer for templates
- A type of database query helper
- A framework of hooks that processes requests and responses globally before reaching views (Correct answer)
- A set of built-in authentication functions
Correct answer: A framework of hooks that processes requests and responses globally before reaching views
Middleware is a series of hooks in Django's request/response lifecycle that allows global processing such as authentication, session handling, and CSRF protection.
Question 22: What is Django REST Framework (DRF)?
- A powerful toolkit for building Web APIs on top of Django (Correct answer)
- Django's built-in JSON serialization library
- A frontend framework for Django projects
- A database migration tool for REST-style schemas
Correct answer: A powerful toolkit for building Web APIs on top of Django
DRF is a third-party package that extends Django with serializers, viewsets, authentication classes, and browsable API tooling for building RESTful APIs.
Question 23: Which tool is used in Django to mock database queries and avoid hitting the real database in unit tests?
- django.db.test.Mock
- django.test.mock
- pytest.monkeypatch only
- unittest.mock.patch (Correct answer)
Correct answer: unittest.mock.patch
Python's unittest.mock.patch is the standard way to mock functions, including Django ORM calls, in unit tests.
Question 24: What Django command should you use to see the database of an existing or legacy?
- manage.py inspectdb (Correct answer)
- manage.py legacydb
- manage.py inspect
- django-admin.py
Correct answer: manage.py inspectdb
The `manage.py inspectdb` command is used in Django to introspect an existing database and output a Django model definition for each table. This is particularly useful when working with a legacy database that was not created by Django, as it helps generate the initial `models.py` file. It allows developers to quickly integrate an existing database into a Django project without manually writing all model classes.
Question 25: 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 the @namespace decorator on views
- Use unique URL names across all apps
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 26: What function reverses a URL pattern by name in Django?
- reverse() (Correct answer)
- resolve()
- url()
- geturl()
Correct answer: reverse()
reverse() takes a URL name and optional arguments to generate the corresponding URL string, avoiding hardcoded URLs.
Question 27: What does the `{% url 'viewname' %}` template tag do?
- Renders a form action URL
- Includes a template at the given URL
- Links to an external URL
- Generates a URL for the named view, reversing the URL pattern (Correct answer)
Correct answer: Generates a URL for the named view, reversing the URL pattern
{% url %} calls Django's reverse() function at template render time to produce the correct URL for a named view, avoiding hardcoded paths.
Question 28: What is the `request.POST` object in Django?
- The parsed JSON body of a request
- A list of uploaded files
- A dict of URL query parameters
- A QueryDict containing data from a POST request body (Correct answer)
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 29: When using `self.assertContains(response, 'text', count=2)`, what does the `count` parameter do?
- Asserts the text appears exactly 2 times in the response (Correct answer)
- Asserts the response was returned in under 2 seconds
- Asserts at least 2 bytes were returned
- 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 30: What does DRF's `@action` decorator do on a ViewSet method?
- Caches the result of the ViewSet method
- Adds authentication to a single ViewSet method
- Marks a method as asynchronous
- Creates a custom endpoint on the ViewSet beyond the standard CRUD actions (Correct answer)
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 31: 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 32: Which filter formats a number with commas as thousands separators in Django templates?
- thousands
- numberformat
- comma
- intcomma (Correct answer)
Correct answer: intcomma
The intcomma filter from django.contrib.humanize formats integers with commas, e.g., 1000000 becomes 1,000,000; requires {% load humanize %}.
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