Django Mcqs
Django Mcqs
After logging in, they should be redirected to their dashboard. Which Django feature will
handle the redirection after login?
a) RedirectView
b) LoginView
c) @login_required
d) LOGIN_REDIRECT_URL
Answer: d) LOGIN_REDIRECT_URL
2. You have an e-commerce site built with Django, and users frequently submit reviews.
You want to ensure that each user can only submit one review per product. How would
you enforce this in the model?
a) unique=True on the review field
b) Add a UniqueConstraint combining user and product fields
c) Use a ForeignKey with unique=True
d) Validate it in the forms.py file
3. Your Django Rest Framework API needs to return data for both admin and regular users,
but you need to filter sensitive data for regular users. How would you customize the
serializer for this?
a) Use SerializerMethodField to control the output
b) Override the __str__ method
c) Use get_serializer_class() in views
d) Define a custom save() method in the model
4. You are creating a Django application that allows users to upload profile pictures. You
want to restrict the file size to a maximum of 5 MB. How do you enforce this in Django?
a) Use a FileField with max_size argument
b) Use a custom validator in the model
c) Set the FileField's upload_to argument
d) Limit it in the template file
Answer: b) Use a custom validator in the model
5. Your Django application allows users to create blog posts. To ensure the post title
remains unique across all users, how would you enforce this constraint in the database?
a) Add a unique constraint on the title field
b) Use CharField with max_length=200
c) Use TextField for the title
d) Add null=False in the field definition
6. You are using Django Rest Framework for an API that lists blog posts. The list should be
paginated to show 10 items per page. Which setting would achieve this?
a) PAGE_SIZE = 10
b) REST_FRAMEWORK['DEFAULT_PAGINATION_CLASS']
c) DEFAULT_FILTER_BACKENDS
d) MAX_PAGE_SIZE = 10
Answer: b) REST_FRAMEWORK['DEFAULT_PAGINATION_CLASS']
7. In your Django project, you want to execute custom logic every time a user model is
saved. How do you achieve this?
a) Override the save() method in the model
b) Use a pre-save signal
c) Use a post-save signal
d) Override the __str__() method
8. You need to store user passwords in a Django application securely. Which of the
following options is best for password storage?
a) Store the password as plain text
b) Use the hashlib library for hashing passwords
c) Use Django's built-in User model with make_password()
d) Store passwords using AES encryption
Answer: c) Use Django's built-in User model with make_password()
9. You are building an API with Django Rest Framework where users need to be
authenticated with JWT tokens. Which of the following libraries would you use to
implement JWT authentication?
a) djangorestframework-simplejwt
b) OAuthlib
c) Django-Token-Auth
d) Django-Session-Auth
Answer: a) djangorestframework-simplejwt
10. In your Django Rest Framework project, you have a Product model that is frequently
updated by multiple users. You want to return a 409 Conflict error when two users
attempt to update the same product simultaneously. How would you achieve this?
a) Use Django’s F() expressions
b) Implement optimistic locking in the serializer
c) Use update_or_create() method
d) Use the save() method directly in the view
11. You need to implement JWT token-based authentication for an API where the token
should expire after 1 hour. Which setting should you modify?
a) ACCESS_TOKEN_LIFETIME in the Simple JWT configuration
b) JWT_SECRET_KEY
c) REFRESH_TOKEN_LIFETIME
d) SESSION_EXPIRATION_TIME
12. In your Django application, a Book model has a foreign key to an Author model. How do
you fetch all books written by a particular author using Django ORM?
a) Book.objects.get(author=author)
b) Book.objects.filter(author=author)
c) Author.objects.filter(book__title=title)
d) Book.objects.filter(author__name=author)
Answer: b) Book.objects.filter(author=author)
13. In Django Rest Framework, you need to handle a POST request to create a new Order.
How do you handle the validation of the request data before saving it to the database?
a) Use form_valid() method
b) Override the create() method in the serializer
c) Use a SerializerMethodField in the serializer
d) Use a ManyToManyField in the model
14. You are developing a Django application that needs to send emails to users when they
register. What Django feature would you use to configure and send these emails?
a) Django Middleware
b) EmailMessage class from django.core.mail
c) Django Sessions
d) Django Caching
15. You are working on a Django Rest Framework API that lists a large dataset. To reduce the
load on the database, you decide to use query optimization. Which of the following
methods would improve performance by reducing the number of database queries?
a) Use filter()
b) Use select_related()
c) Use count()
d) Use order_by()
16. Your Django model contains sensitive user data, and you need to restrict access based
on user roles. What is the best way to enforce role-based permissions in Django Rest
Framework?
a) Use IsAuthenticated permission
b) Use custom permissions in DRF
c) Define user roles in the urls.py file
d) Implement @admin_required decorator
17. You are building a Django application that allows users to reset their passwords. Which
built-in Django view would you use to handle the password reset process?
a) PasswordChangeView
b) PasswordResetConfirmView
c) PasswordResetView
d) ResetView
Answer: c) PasswordResetView
18. In a Django Rest Framework project, you need to create a serializer that includes a
nested relationship between models. What field type should you use to handle nested
objects in the serializer?
a) PrimaryKeyRelatedField
b) ManyToManyField
c) SerializerMethodField
d) NestedSerializer
Answer: a) PrimaryKeyRelatedField
19. You are creating a Django model for a product catalog, and some products are only
available in specific countries. How do you define a field that allows the selection of
multiple countries for a product?
a) Use a ForeignKey field
b) Use a CharField with choices
c) Use a ManyToManyField to a Country model
d) Use a OneToOneField with a Country model
21. You are developing a Django application that requires users to be authenticated to
access specific pages. How do you enforce authentication for a particular view?
a) Use the @login_required decorator
b) Override the save() method in the view
c) Use a custom form validation method
d) Implement session management in urls.py
22. Your Django application uses JWT tokens for authentication. You need to allow users to
refresh their JWT tokens after they expire. Which token type is used for this purpose?
a) Access token
b) Refresh token
c) ID token
d) Authorization token
23. You are working on a Django Rest Framework API where a user can upload a file. You
want to restrict the file size and type. How can you enforce this in your API?
a) Override the create() method in the view
b) Implement validation in the serializer
c) Restrict it in the model definition
d) Handle it in the frontend JavaScript
Answer: c) Use DjangoFilterBackend and specify the filter fields in the view
25. In your Django project, you want to limit a queryset based on the logged-in user’s
permissions. What’s the best way to handle this?
a) Use filter() with a custom permission decorator
b) Override get_queryset() in the view
c) Implement it in urls.py
d) Use ManyToManyField for permissions in the model
26. Your Django Rest Framework API provides detailed information about a book when given
the book's ID. Which method in DRF views should you use to handle GET requests for
this specific resource?
a) list()
b) retrieve()
c) create()
d) update()
Answer: b) retrieve()
27. In a Django application, you want to prefetch related objects to reduce the number of
database queries. Which Django ORM method should you use to achieve this?
a) select_related()
b) annotate()
c) get_queryset()
d) values()
Answer: a) select_related()
28. Your Django application needs to log out a user when their JWT token expires. Which
setting in django-rest-framework-simplejwt handles automatic token expiration and
refresh?
a) TOKEN_REFRESH_LIFETIME
b) ROTATE_REFRESH_TOKENS
c) ACCESS_TOKEN_LIFETIME
d) JWT_EXPIRATION
Answer: c) ACCESS_TOKEN_LIFETIME
29. You are building an API in Django Rest Framework to handle image uploads. How can
you limit the maximum file size and validate the image format?
a) Use ImageField with max_length
b) Define custom validators in the serializer
c) Limit file size in the views.py
d) Use FileField with max_length
30. You want to allow users to perform a partial update on a resource in Django Rest
Framework. Which method should be used to handle partial updates in DRF views?
a) post()
b) patch()
c) put()
d) get()
Answer: b) patch()
31. You are designing a multi-tenant Django application where each user should only have
access to their own data. How do you filter queryset results to ensure this security?
a) Implement filtering in the templates
b) Use get_object_or_404() with user data
c) Override the get_queryset() method to include user-specific filtering
d) Use get_context_data() in class-based views
33. You want to add pagination to a Django Rest Framework API to display 20 items per
page. How do you configure this?
a) Set PAGINATE_BY in the view
b) Set PAGINATE_BY_PARAM in the view
c) Configure PAGE_SIZE in settings
d) Use max_limit in the view
34. In your Django Rest Framework project, you want to filter queryset results dynamically
based on query parameters passed in the URL. Which method would allow you to
achieve this?
a) filter_queryset()
b) get()
c) get_queryset()
d) get_context_data()
Answer: a) filter_queryset()
35. You are developing a Django application where users can update their profiles. However,
only certain fields like first_name and last_name can be updated. How do you restrict
the update operation to specific fields?
a) Define allowed fields in the views.py
b) Use the partial=True argument in the serializer
c) Use read_only=True in the model definition
d) Override save() method in the view
Answer: b) DEFAULT_AUTHENTICATION_CLASSES
37. You need to cache expensive database queries to optimize performance in your Django
application. Which caching backend would you use to cache the query results?
a) Django Sessions
b) Django Middleware
c) Redis or Memcached
d) Django Templates
38. Your Django project requires a view that returns data in JSON format for an API. Which
view class would you use to automatically convert the response to JSON?
a) TemplateView
b) DetailView
c) JsonResponse
d) RedirectView
Answer: c) JsonResponse
39. You want to add a custom method to a Django Rest Framework serializer to include
additional data in the response that is not part of the model. Which serializer field would
you use for this?
a) CharField
b) BooleanField
c) SerializerMethodField
d) ModelSerializer
Answer: c) SerializerMethodField
40. Your Django project has a Category model with a foreign key to Product. How do you
retrieve all categories that have no products assigned to them using Django ORM?
a) Category.objects.filter(product=None)
b) Category.objects.exclude(product__isnull=False)
c) Category.objects.filter(product__isnull=True)
d) Category.objects.filter(product__count=0)
Answer: c) Category.objects.filter(product__isnull=True)
41. In your Django application, you need to restrict access to views based on the user’s role.
How do you define role-based access control in Django Rest Framework?
a) Use IsAuthenticated permission class
b) Define custom permission classes
c) Add user role checks in urls.py
d) Use the login_required decorator
42. You are working on a Django project where you need to create a custom management
command. Which directory structure is appropriate for defining custom management
commands in a Django app?
a) app/management/commands/
b) app/utils/commands/
c) app/views/commands/
d) app/templates/commands/
Answer: a) app/management/commands/
43. You have a Django Rest Framework viewset where different user roles have different
access levels. How do you define permissions for different actions such as list(), create(),
and delete()?
a) Use IsAuthenticated globally
b) Set permissions in the urls.py
c) Use get_permissions() to define different permissions for each action
d) Use Django Middleware to handle access
44. You are building an API that allows users to update their account details, but you want to
ensure that they can only update their own account. Which method would you override
in Django Rest Framework to enforce this check?
a) update()
b) perform_update()
c) partial_update()
d) get_queryset()
Answer: b) perform_update()
45. You are using JWT-based authentication in Django Rest Framework. After login, the user
receives an access token. How do you ensure that the token is included in all future
requests from the frontend?
a) Store the token in the session
b) Send the token in the Authorization header of every request
c) Include the token in the request body
d) Use cookies to store the token
46. In your Django ORM query, you need to calculate the average price of products in each
category. Which ORM function would you use?
a) annotate() with Avg()
b) aggregate() with Sum()
c) filter() with Avg()
d) annotate() with Count()
47. You are building a Django Rest Framework API where users can register and login. Upon
login, you need to return both an access token and a refresh token. Which library can
help you implement this?
a) rest_framework_simplejwt
b) django-rest-auth
c) django-otp
d) djangorestframework-recursive
Answer: a) rest_framework_simplejwt
48. You want to prevent users from updating certain fields of a model in your Django Rest
Framework API while allowing other fields to be editable. Which option best handles this
scenario?
a) Define the non-editable fields in the serializer with read_only=True
b) Override the validate() method in the serializer
c) Define these fields as null=True in the model
d) Use permissions in the view
49. In Django ORM, how can you order query results by a field in descending order?
a) Model.objects.order_by('-field_name')
b) Model.objects.order_by('desc_field_name')
c) Model.objects.filter('-field_name')
d) Model.objects.sort('-field_name')
Answer: a) Model.objects.order_by('-field_name')
50. You need to update the password for a user in your Django Rest Framework API, but you
want to ensure that the password is hashed properly. How would you handle this?
a) Use set_password() on the user object
b) Use save() method without changes
c) Encrypt the password manually in the view
d) Store the password in plain text and then hash it later
Answer: b) IsAuthenticated
52. In your Django project, you want to retrieve objects in batches to improve performance
for large datasets. Which Django ORM function should you use?
a) all()
b) filter()
c) iterator()
d) get()
Answer: c) iterator()
53. You want to ensure that only users with an active status can log in to your Django
application. How do you enforce this in Django Rest Framework?
a) Override the login() view
b) Use IsAuthenticated permission
c) Override the authenticate() method
d) Set a custom user model and check the is_active flag
Answer: d) Set a custom user model and check the is_active flag
54. In Django ORM, how can you exclude specific objects from a query result?
a) Use filter() with NOT condition
b) Use exclude()
c) Use annotate()
d) Use exclude() with ManyToManyField
Answer: b) RateThrottle
56. You need to add a "created_at" timestamp to your Django models that automatically
sets the current date and time when a record is created. Which field type should you
use?
a) DateField(auto_now=True)
b) DateTimeField(auto_now_add=True)
c) DateTimeField()
d) DateField()
Answer: b) DateTimeField(auto_now_add=True)
57. In your Django Rest Framework API, you want to give anonymous users read access but
restrict write access to authenticated users. Which permission class should you use?
a) IsAuthenticated
b) AllowAny
c) IsAdminUser
d) IsAuthenticatedOrReadOnly
Answer: d) IsAuthenticatedOrReadOnly
58. You want to write a custom Django management command that clears old user sessions
from the database. In which directory should you place the custom command file?
a) app/utils/commands/
b) app/management/commands/
c) app/migrations/commands/
d) app/views/commands/
Answer: b) app/management/commands/
59. In your Django ORM query, you want to get the total number of comments per blog
post. Which function will allow you to count the related comments?
a) aggregate(Count('comments'))
b) annotate(Count('comments'))
c) count()
d) select_related('comments')
Answer: b) annotate(Count('comments'))
60. Your Django application requires a custom user model to include additional fields such
as phone_number. How do you define a custom user model in Django?
a) Override the User model directly
b) Subclass AbstractUser and define the new fields
c) Modify the default user model in settings.py
d) Use ForeignKey to add extra fields to the user
61. You are developing an API in Django Rest Framework where you want to return
paginated results for a list of items. How can you add pagination globally to your API
views?
a) Set PAGINATE_BY in the view
b) Add pagination settings in settings.py
c) Use PageNumberPagination in each view
d) Define a custom pagination class
62. You want to query the last 10 records of a model in Django ORM, sorted by creation
date. Which method would you use?
a) Model.objects.filter().limit(10)
b) Model.objects.all()[:10]
c) Model.objects.order_by('-created_at')[:10]
d) Model.objects.last(10)
Answer: c) Model.objects.order_by('-created_at')[:10]
63. In your Django project, you want to implement caching for API responses to improve
performance. Which middleware should you use to add caching?
a) SessionMiddleware
b) CacheMiddleware
c) SecurityMiddleware
d) CorsMiddleware
Answer: b) CacheMiddleware
64. In Django ORM, how do you retrieve only distinct values from a queryset to eliminate
duplicates?
a) Model.objects.unique()
b) Model.objects.exclude()
c) Model.objects.distinct()
d) Model.objects.filter()
Answer: c) Model.objects.distinct()
65. You are building a REST API with Django Rest Framework and want to use token-based
authentication. Which authentication class should you use?
a) BasicAuthentication
b) TokenAuthentication
c) SessionAuthentication
d) OAuth2Authentication
Answer: b) TokenAuthentication
66. You want to filter a queryset in Django ORM based on multiple conditions that must all
be true. How do you accomplish this?
a) Use filter() with Q() objects
b) Use exclude()
c) Use annotate()
d) Use all()
68. Your Django application needs to handle form submissions via AJAX. Which HTTP
method will you primarily use to submit the data from the client-side?
a) GET
b) POST
c) PUT
d) PATCH
Answer: b) POST
69. In your Django ORM query, you want to retrieve records where a foreign key field is null.
How would you filter this queryset?
a) filter(foreign_key__isnull=False)
b) filter(foreign_key__isnull=True)
c) exclude(foreign_key__isnull=True)
d) filter(foreign_key=None)
Answer: b) filter(foreign_key__isnull=True)
70. You want to secure your Django Rest Framework API by allowing only HTTPS
connections. Which setting should you modify?
a) USE_HTTPS
b) SECURE_SSL_REDIRECT
c) ALLOW_HTTPS_ONLY
d) CSRF_USE_SSL
Answer: b) SECURE_SSL_REDIRECT
71. In Django ORM, how can you prefetch related objects to optimize database queries for
many-to-many relationships?
a) select_related()
b) annotate()
c) values()
d) prefetch_related()
Answer: d) prefetch_related()
72. You want to define custom actions for a Django Rest Framework ModelViewSet. Where
should you define these custom actions?
a) In the serializer
b) In the urls.py file
c) In the viewset using @action decorator
d) In the model
73. Your Django project needs to send a confirmation email to users after they register.
Which Django feature would you use to send emails?
a) Django Celery
b) Django Signals
c) Django Email Backend
d) Django Tasks
74. You are implementing a JWT-based authentication system for your API. How would you
securely store the JWT token on the client-side?
a) Store it in local storage
b) Store it in a session cookie with HttpOnly flag
c) Include it in the URL parameters
d) Store it in a regular cookie
76. You are building a Django application that uses multiple databases. How do you
configure Django to route queries to different databases?
a) Use DATABASES setting in settings.py
b) Use db_for_read and db_for_write in the model
c) Define separate models for each database
d) Use Django's router.py
77. You want to ensure that only authenticated users can create new objects in your Django
Rest Framework API, but allow unauthenticated users to view objects. How can you
achieve this?
a) Use AllowAny permission
b) Use IsAuthenticated for POST requests and AllowAny for GET
c) Use IsAuthenticated for all requests
d) Override the perform_create() method
Answer: b) Use IsAuthenticated for POST requests and AllowAny for GET
78. In Django ORM, you want to update multiple fields of an object in a single query. Which
method should you use?
a) save()
b) update()
c) bulk_update()
d) create()
Answer: b) update()
79. You want to handle different HTTP methods (e.g., GET, POST) for the same URL in a
Django Rest Framework view. How can you differentiate between these methods in
a APIView?
a) Override perform_action()
b) Use action_map
c) Define separate views for each method
d) Use get(), post(), etc., methods
80. Your Django Rest Framework API is facing performance issues when dealing with a large
number of queries in related models. How can you optimize this?
a) Use annotate() to reduce queries
b) Use select_related() for foreign key relations
c) Use distinct() to reduce duplicate queries
d) Use prefetch_related() for filtering
81. You are building a Django Rest Framework API that allows users to upload files. You want
to set a limit on the file types that can be uploaded. Where should you enforce this
restriction?
a) In the views.py file
b) In the models.py file
c) In the serializers.py file using a custom validator
d) In the settings.py file
82. You want to run specific actions after an instance is saved in Django ORM, such as
sending a notification. Which method should you override in the model to achieve this?
a) pre_save()
b) post_save()
c) save()
d) clean()
Answer: c) save()
83. In a Django Rest Framework project, you need to validate input data before saving it to
the database. Which method should you override in your serializer class?
a) save()
b) validate()
c) is_valid()
d) create()
Answer: b) validate()
84. You are building a Django project that uses a large number of related models. To
improve query performance when accessing related objects, which method should you
use?
a) prefetch_related()
b) select_related()
c) annotate()
d) order_by()
Answer: b) select_related()
85. In your Django Rest Framework project, you want to handle different media types in
your API response, such as JSON and XML. How do you achieve this?
a) Use DEFAULT_RENDERER_CLASSES in settings.py
b) Set a ContentType header in views
c) Override get_serializer() method
d) Use ContentNegotiation class
86. You are creating a REST API in Django Rest Framework and want to send email
notifications when a new user registers. Where should you implement this functionality?
a) In the views.py file
b) In the models.py file using signals
c) In the serializers.py file
d) In settings.py
Answer: a) contains
88. Your Django Rest Framework project requires you to authenticate users using JWT
tokens. Which library would you use to implement JWT-based authentication in DRF?
a) rest_framework_simplejwt
b) djangorestframework-jwt
c) django-rest-auth
d) oauthlib
Answer: a) rest_framework_simplejwt
89. You need to perform a bulk update on multiple records in Django ORM in a single query.
Which method should you use?
a) bulk_update()
b) update()
c) save()
d) create()
Answer: a) bulk_update()
90. In your Django Rest Framework API, you want to return different responses for users
with different roles (e.g., admin, regular user). How can you achieve this?
a) Override the get() method in the view
b) Use a custom permission class
c) Check the user role in the serializer
d) Use is_valid() to differentiate roles
91. You are building a multi-tenant Django application where each user can only access their
own data. How do you restrict access in Django Rest Framework?
a) Use permissions.IsAuthenticated
b) Override get_queryset() method in the view
c) Use AllowAny permission
d) Filter by user in the serializer
92. In your Django project, you want to schedule periodic tasks such as clearing expired
sessions. Which library should you use to schedule these tasks?
a) Django Signals
b) Django Celery
c) Django Cache
d) Django Middleware
93. You need to retrieve the first object from a Django ORM queryset, or return None if no
objects are found. Which method should you use?
a) get()
b) first()
c) last()
d) filter()
Answer: b) first()
94. In your Django Rest Framework project, you want to prevent users from making too
many API requests within a short period. Which feature would you implement?
a) Permission Classes
b) Rate Limiting
c) Authentication Classes
d) Request Throttling
95. You need to create a custom field in a Django model that stores a calculated value based
on other fields. Where should you define this logic?
a) In the views.py file
b) In the models.py file using @property
c) In the serializers.py file
d) In the database schema
96. You are using Django Rest Framework to create an API where each resource has a unique
identifier. How do you configure the serializer to ensure each resource has a unique ID?
a) Set unique=True on the ID field in the model
b) Override the save() method in the serializer
c) Set the read_only flag for the ID field in the serializer
d) Use unique_together in the model
97. In Django ORM, you want to create multiple related objects in a single transaction.
Which method would you use to ensure atomicity?
a) commit()
b) bulk_create()
c) transaction.atomic()
d) save()
Answer: c) transaction.atomic()
98. You need to provide pagination support for your Django Rest Framework API. How can
you configure pagination globally for all API views?
a) Set PAGINATE_BY in the view
b) Add DEFAULT_PAGINATION_CLASS in settings.py
c) Override paginate_queryset() in each view
d) Use a custom pagination class
99. Your Django application requires a custom login view where users can log in with their
email address instead of their username. Where would you implement this custom
authentication logic?
a) In the urls.py file
b) In a custom authenticate() method in the backend
c) In the forms.py file
d) In settings.py
100. You need to perform a full-text search on a CharField in your Django model.
Which feature should you enable to optimize this search?
a) select_related()
b) prefetch_related()
c) search_vector
d) filter()
Answer: c) search_vector