W3Schools Django Certification Exam — Questions and Answers
Question 1: How do you apply a template filter to a variable in Django?
- {{ value|filtername }} (Correct answer)
- {% filter value %}
- {{ filtername(value) }}
- {{ 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 2: What does DRF's `@action` decorator do on a ViewSet method?
- Adds authentication to a single ViewSet method
- Caches the result of the ViewSet method
- Creates a custom endpoint on the ViewSet beyond the standard CRUD actions (Correct answer)
- Marks a method as asynchronous
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 3: Which Django template filter converts a string to all uppercase?
- strtoupper
- upcase
- capitalize
- upper (Correct answer)
Correct answer: upper
The upper filter converts all characters in the string to uppercase, e.g., {{ 'hello'|upper }} outputs 'HELLO'.
Question 4: Which Django view class is best for displaying and processing a single model's create form?
- UpdateView
- FormView
- CreateView (Correct answer)
- 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 5: What does `request.user.is_authenticated` return for an anonymous user?
- Raises AttributeError
- True
- False (Correct answer)
- None
Correct answer: False
For anonymous users, Django provides an AnonymousUser object whose is_authenticated property always returns False.
Question 6: Which function authenticates a user with a username and password in Django?
- auth.verify(username, password)
- login(request, username, password)
- User.check_password(password)
- authenticate(request, username=username, password=password) (Correct answer)
Correct answer: authenticate(request, username=username, password=password)
authenticate() checks credentials against all configured authentication backends and returns a User object on success or None on failure.
Question 7: What does `{{ forloop.counter }}` provide inside a Django for loop?
- The 1-based index of the current loop iteration (Correct answer)
- The total number of items in the loop
- The 0-based index of the current loop iteration
- 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 8: 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 9: Which Django command applies pending database migrations to the database?
- python manage.py migrate (Correct answer)
- python manage.py makemigrations
- python manage.py runserver
- python manage.py syncdb
Correct answer: python manage.py migrate
The migrate command applies migration files to the database schema.
Question 10: What is the purpose of Django's `Meta` class inside a model?
- To define model-level options like ordering and table name (Correct answer)
- To register the model with the admin
- To define model methods only
- To store model instance data
Correct answer: To define model-level options like ordering and table name
The inner Meta class allows you to set model-level metadata such as ordering, verbose_name, db_table, and unique_together constraints.
Question 11: Which template tag is used to extend a base template in Django?
- {% parent 'base.html' %}
- {% extends 'base.html' %} (Correct answer)
- {% include 'base.html' %}
- {% inherit '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 12: What does settings.py do?
- It's used to configure settings for the Django project (Correct answer)
- It's used to change the settings of an app.
- It's used to configure the server's date and time
- It's used to sync the database schema
Correct answer: It's used to configure settings for the Django project
The `settings.py` file is the central configuration hub for a Django project, defining all its operational parameters. It contains crucial settings such as database connections, installed applications, middleware, template configurations, static file paths, and security keys. Modifying this file allows developers to customize how their Django application behaves and interacts with its environment.
Question 13: What does the `{% block %}` tag do in Django templates?
- Defines a named region in a parent template that child templates can override (Correct answer)
- Conditionally renders content
- Includes a static file
- Loops over a list of items
Correct answer: Defines a named region in a parent template that child templates can override
{% block name %}...{% endblock %} defines a replaceable region in a parent template, which child templates override using the same block name.
Question 14: How do you restrict a ModelForm to only a subset of model fields?
- Use the limit_fields= argument on ModelForm
- Override __init__ to remove fields
- Subclass the model with fewer fields
- Set fields = ['field1', 'field2'] or exclude = ['field3'] in Meta (Correct answer)
Correct answer: Set fields = ['field1', 'field2'] or exclude = ['field3'] in Meta
The fields list in Meta explicitly whitelists fields to include, while exclude blacklists fields; using fields is preferred for security.
Question 15: What is the difference between a function-based view (FBV) and a class-based view (CBV) in Django?
- 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
- FBVs support only GET; CBVs support all methods
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 16: What is the purpose of Django's `SecurityMiddleware`?
- Sanitizes user input against XSS
- Sets security headers like HSTS, X-Content-Type-Options, and enforces HTTPS (Correct answer)
- Encrypts session cookies
- Rate-limits requests per IP
Correct answer: Sets security headers like HSTS, X-Content-Type-Options, and enforces HTTPS
SecurityMiddleware handles several security-related HTTP headers and redirects HTTP to HTTPS based on settings like SECURE_HSTS_SECONDS and SECURE_SSL_REDIRECT.
Question 17: In Django, how many various kinds of HTTP requests are there?
- 4
- 6
- 5
- 2 (Correct answer)
Correct answer: 2
While HTTP defines several request methods (GET, POST, PUT, DELETE, etc.), in the context of typical web forms and basic interactions, Django primarily distinguishes between two main types of requests: GET and POST. GET requests are used to retrieve data and are idempotent, while POST requests are used to submit data and can have side effects. Django's `request.method` attribute allows you to easily check for these two common types.
Question 18: Which HttpResponse subclass performs a permanent redirect in Django?
- HttpResponseMovedPermanently
- HttpResponseForward
- HttpResponsePermanentRedirect (Correct answer)
- HttpResponseRedirect
Correct answer: HttpResponsePermanentRedirect
HttpResponsePermanentRedirect returns a 301 status code, while HttpResponseRedirect returns a 302 temporary redirect.
Question 19: 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 20: 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
- Converts the form to a PDF
- Outputs the form's action URL
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 21: What is Django's `AbstractUser` model used for?
- Extending the built-in User model with additional fields while keeping all default auth features (Correct answer)
- Creating users without database tables
- Defining permission groups
- Building API token-based authentication
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 22: What does the `unique=True` argument on a model field enforce?
- That no two rows can have the same value for that field (Correct answer)
- That the field is indexed for faster lookup
- That the field is the primary key
- That the field cannot be NULL
Correct answer: That no two rows can have the same value for that field
Setting unique=True creates a UNIQUE constraint in the database, ensuring no two model instances share the same field value.
Question 23: Which CBV mixin is used to restrict a class-based view to authenticated users?
- SecureMixin
- PermissionMixin
- AuthRequiredMixin
- LoginRequiredMixin (Correct answer)
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 24: Which response object should a view return to send JSON data in Django?
- ApiResponse
- JsonResponse (Correct answer)
- JSONResponse
- HttpResponse with content_type='application/json'
Correct answer: JsonResponse
JsonResponse is a subclass of HttpResponse that serializes a dictionary to JSON and sets the Content-Type to application/json automatically.
Question 25: Which DRF serializer automatically generates fields from a model?
- AutoSerializer
- FieldSerializer
- ModelSerializer (Correct answer)
- SchemaSerializer
Correct answer: ModelSerializer
ModelSerializer introspects a model to create serializer fields automatically, similar to how ModelForm works for forms.
Question 26: Which abstract base class makes a model function as an abstract base, not creating its own database table?
- Setting db_table = None in Meta
- Using @abstract decorator
- Inheriting from AbstractModel
- Setting abstract = True in Meta (Correct answer)
Correct answer: Setting abstract = True in Meta
Setting abstract = True in the model's Meta class tells Django not to create a database table for that model; subclasses get their own tables with inherited fields.
Question 27: What is the `{% csrf_token %}` tag used for in Django forms?
- Encrypts form data before submission
- Generates a nonce for Content Security Policy
- Validates form input on the client side
- 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 28: Which built-in Django validator enforces a minimum numeric value on a form field?
- MinLengthValidator
- RangeValidator
- MinValueValidator (Correct answer)
- LowerBoundValidator
Correct answer: MinValueValidator
MinValueValidator from django.core.validators raises a ValidationError if the field's value is less than the specified minimum.
Question 29: What is the `request.POST` object in Django?
- A QueryDict containing data from a POST request body (Correct answer)
- A list of uploaded files
- The parsed JSON body of a request
- A dict of URL query parameters
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 30: What does `select_related()` do in a Django QuerySet?
- Lazy-loads related objects on access
- Caches QuerySet results in memory
- Performs a SQL JOIN to fetch related objects in a single query (Correct answer)
- Prefetches many-to-many related objects
Correct answer: Performs a SQL JOIN to fetch related objects in a single query
select_related() follows ForeignKey and OneToOneField relationships and performs a SQL JOIN, reducing the number of database queries.
Question 31: What syntax is used to output a variable in a Django template?
- ${variable}
- {{ variable }} (Correct answer)
- <% variable %>
- {% 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 32: What does `form.save()` do on a Django ModelForm?
- Saves the form HTML to a file
- Creates or updates the model instance based on the form's cleaned data (Correct answer)
- Persists form errors to the database
- Stores form data in the session
Correct answer: Creates or updates the model instance based on the form's cleaned data
ModelForm.save() creates a new instance or updates an existing one (if bound to an instance) using the validated cleaned_data.
Question 33: How does DRF's `ModelSerializer` handle the `create()` method by default?
- It uses Django's form save() method
- It calls Model.objects.create() with the validated data (Correct answer)
- It raises NotImplementedError requiring manual implementation
- It calls the model's __init__ and then save()
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 34: What does `login(request, user)` do in Django?
- Verifies the user's credentials
- Generates an authentication token
- Creates a new user account
- Attaches the user to the session and marks them as logged in (Correct answer)
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 35: What is DRF's `Router` used for?
- Routing requests to different database shards
- Defining API versioning schemes
- Load balancing API requests
- Automatically generating URL patterns for ViewSet actions (Correct answer)
Correct answer: Automatically generating URL patterns for ViewSet actions
Registering a ViewSet with a Router auto-creates standard REST URL patterns for list, detail, create, update, and delete actions.
Question 36: 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>.
Question 37: What does the `{% include %}` tag do in Django templates?
- Inherits from a parent template
- Renders another template and inserts its output into the current template (Correct answer)
- Imports a Python module
- Loads a template tag library
Correct answer: Renders another template and inserts its output into the current template
{% include 'snippet.html' %} renders the named template with the current context and inserts the result inline, useful for reusable partials.
Question 38: What does `get_object_or_404()` do in a Django view?
- Filters objects and returns 404 on empty sets
- Fetches an object or creates it if not found
- Returns None instead of raising DoesNotExist
- Fetches an object or returns a 404 response if not found (Correct answer)
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 39: Which DRF permission class allows unrestricted access to an endpoint?
- OpenAccess
- AllowAny (Correct answer)
- IsPublic
- NoAuth
Correct answer: AllowAny
AllowAny grants access to any request, authenticated or not, and is useful for public endpoints like registration or password reset.
Question 40: What function reverses a URL pattern by name in Django?
- resolve()
- url()
- reverse() (Correct answer)
- geturl()
Correct answer: reverse()
reverse() takes a URL name and optional arguments to generate the corresponding URL string, avoiding hardcoded URLs.
Question 41: What is the purpose of `prefetch_related()` in Django ORM?
- Fetches many-to-many and reverse ForeignKey relations in separate optimized queries (Correct answer)
- Performs a single JOIN query for all relations
- Pre-loads all model fields
- Caches model instances in Redis
Correct answer: Fetches many-to-many and reverse ForeignKey relations in separate optimized queries
prefetch_related() does separate queries for each relationship and performs the joining in Python, which is optimal for many-to-many and reverse FK lookups.
Question 42: Which template tag iterates over a list in Django?
- {% iterate item in list %}
- {% for item in list %} (Correct answer)
- {% loop item in list %}
- {% each item in list %}
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 a Django formset?
- A form factory for dynamically created forms
- A group of form widgets sharing a layout
- A collection of forms that allows processing multiple form instances at once (Correct answer)
- A set of form validation rules
Correct answer: A collection of forms that allows processing multiple form instances at once
A formset manages multiple instances of the same form, handling rendering, validation, and saving of multiple objects in a single POST.
Question 44: What does the `null=True` argument on a Django model field do?
- Allows the field to store NULL in the database (Correct answer)
- Sets the default value to None in Python
- Makes the field optional in forms
- Skips validation for this field
Correct answer: Allows the field to store NULL in the database
null=True allows the database column to store a NULL value; for string-based fields, Django convention prefers blank=True with an empty string instead.
Question 45: What is the purpose of DRF's `SerializerMethodField`?
- Defines a writable field backed by a Python method
- Serializes a model method's return value automatically
- Creates a dynamic field based on request parameters
- 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 46: What is Django REST Framework (DRF)?
- A frontend framework for Django projects
- Django's built-in JSON serialization library
- A powerful toolkit for building Web APIs on top of Django (Correct answer)
- 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 47: What does the `{% url 'viewname' %}` template tag do?
- Links to an external URL
- Renders a form action URL
- Generates a URL for the named view, reversing the URL pattern (Correct answer)
- Includes a template at the given URL
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 48: Which filter formats a number with commas as thousands separators in Django templates?
- comma
- numberformat
- intcomma (Correct answer)
- thousands
Correct answer: intcomma
The intcomma filter from django.contrib.humanize formats integers with commas, e.g., 1000000 becomes 1,000,000; requires {% load humanize %}.
Question 49: What does Django's CSRF middleware protect against?
- Cross-Site Scripting via template variables
- SQL injection via form inputs
- Cross-Site Request Forgery attacks where malicious sites submit requests on behalf of authenticated users (Correct answer)
- Brute-force login attacks
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 50: In urls.py, what method is used instead of path() to pass regular expressions as routes?
- None of the above
- url() (Correct answer)
- include()
- re_path()
Correct answer: url()
In older versions of Django (prior to 2.0), the `url()` function was the primary way to define URL patterns using regular expressions. While Django 2.0 introduced `path()` for simpler string-based routing, and `re_path()` as its modern regex-based counterpart, `url()` historically served the purpose of allowing developers to specify complex routes using regular expressions.
Question 51: How do you make a DRF API endpoint return XML instead of JSON?
- Set RESPONSE_FORMAT = 'xml' in settings.py
- Use XmlSerializer instead of ModelSerializer
- Add XMLRenderer to the view's renderer_classes and request Accept: application/xml (Correct answer)
- Pass format='xml' to the serializer
Correct answer: Add XMLRenderer to the view's renderer_classes and request Accept: application/xml
DRF uses content negotiation; adding XMLRenderer to renderer_classes and sending Accept: application/xml in the request returns XML output.
Question 52: What is Django middleware?
- A caching layer for templates
- A framework of hooks that processes requests and responses globally before reaching views (Correct answer)
- A set of built-in authentication functions
- A type of database query helper
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 53: Which decorator restricts a view to logged-in users only?
- @requires_login
- @authenticated
- @login_required (Correct answer)
- @auth_required
Correct answer: @login_required
@login_required redirects unauthenticated users to the login page and is imported from django.contrib.auth.decorators.
Question 54: How do you load a custom template tag library in Django?
- {% include mytaglib %}
- {% load mytaglib %} (Correct answer)
- {% import mytaglib %}
- {% use mytaglib %}
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 55: What HTTP status code does Django's `Http404` exception result in?
- 404 (Correct answer)
- 400
- 403
- 500
Correct answer: 404
Raising Http404 causes Django to return a 404 Not Found response, optionally rendering a custom 404.html template.
Question 56: What does the `X-Frame-Options: DENY` header configured via Django's `XFrameOptionsMiddleware` prevent?
- CSRF attacks via embedded forms
- XSS attacks via iframes
- CSS injection attacks
- Clickjacking attacks where the site is embedded in an iframe (Correct answer)
Correct answer: Clickjacking attacks where the site is embedded in an iframe
X-Frame-Options: DENY prevents the page from being rendered in any iframe, protecting against clickjacking where attackers overlay invisible frames to trick users.
Question 57: 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 58: What does DRF's `APIView` class provide over Django's standard `View`?
- Request parsing, authentication, permission checking, and content negotiation for APIs (Correct answer)
- GraphQL schema generation
- Built-in pagination and filtering
- Automatic database CRUD operations
Correct answer: Request parsing, authentication, permission checking, and content negotiation for APIs
APIView wraps Django's View with DRF's Request/Response objects, authentication, permissions, throttling, and content negotiation.
Question 59: 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 60: Which Django setting controls password hashing algorithms?
- PASSWORD_HASH_ALGORITHM
- AUTH_PASSWORD_HASHERS
- SECURITY_HASHERS
- PASSWORD_HASHERS (Correct answer)
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.
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
Practice questions written with AI assistance and published by Nathan Beja, founder of Practice Test Geeks. They are not real exam questions. We have not yet matched this exam's facts to an official source, so confirm fees, dates and rules with the exam body. Editorial policy