Django Comprehensive Quiz & Projects
30 questions on Django Basics Tutorial.
Question 1: In Django's MVT (Model-View-Template) pattern, what is the primary role of the View?
- A. Defining the database table structures and indexes.
- B. Rendering HTML layouts with custom styles.
- C. Handling HTTP requests, executing business logic, and returning responses. β (correct answer)
- D. Managing CSS/JS static assets compilation.
Explanation: The Django View acts as the controller, executing logic, querying database models, and rendering templates.
Question 2: When using the Django ORM, what is the difference between select_related and prefetch_related?
- A. select_related does a SQL JOIN in the database (best for ForeignKey), while prefetch_related does separate queries (best for ManyToMany). β (correct answer)
- B. select_related is asynchronous, whereas prefetch_related is synchronous.
- C. select_related works only with NoSQL, while prefetch_related works with SQL.
- D. select_related is used to write data, while prefetch_related is used to delete data.
Explanation: select_related performs a SQL JOIN to fetch related object data in a single query. prefetch_related queries each table separately and merges results.
Question 3: What does running the command 'python manage.py migrate' accomplish?
- A. Copies static files to the production directory.
- B. Applies pending database schema modifications defined in migrations. β (correct answer)
- C. Migrates the Django server configuration to a new hosting provider.
- D. Backs up database rows into a serialized JSON dump.
Explanation: The migrate command updates the database schema according to the migration files.
Question 4: What are Class-Based Views (CBVs) in Django primarily used for?
- A. Encrypting view payloads using class-based decorators.
- B. Writing views that represent raw SQL queries.
- C. Promoting code reuse and structuring common view patterns (like lists, detail pages) using inheritance. β (correct answer)
- D. Routing dynamic URL requests to secondary app directories.
Explanation: CBVs allow developers to leverage inheritance and generic views to implement common design patterns without repeating code.
Question 5: How does Django protect form submissions from Cross-Site Request Forgery (CSRF) attacks?
- A. By enforcing HTTPS connection encryption on all forms.
- B. By checking the user's IP address against a whitelist.
- C. By embedding a unique, cryptographically signed token in forms and verifying it on POST requests. β (correct answer)
- D. By converting all POST payloads into secure binary blobs.
Explanation: Django's CSRF middleware injects and checks a cryptographically signed csrf_token parameter in all unsafe requests (POST/PUT/DELETE).
Question 6: Which file holds the core configuration settings, database keys, and installed apps list for a Django project?
- A. urls.py
- B. models.py
- C. settings.py β (correct answer)
- D. manage.py
Explanation: settings.py is the central configuration file of any Django project.
Question 7: What is the purpose of Django Migrations?
- A. Moving files from local development to production servers.
- B. A version control system for database schemas, translating Python model code changes into SQL commands. β (correct answer)
- C. Migrating the Django codebase from Python 2 to Python 3.
- D. Transferring media files to cloud storage.
Explanation: Migrations record modifications to models, allowing database updates to be rolled out safely.
Question 8: How do you implement a Many-to-Many relationship in the Django ORM?
- A. models.ForeignKey()
- B. models.ManyToManyField() β (correct answer)
- C. models.OneToOneField()
- D. models.PivotField()
Explanation: ManyToManyField automatically handles creating the necessary intermediary junction table under the hood.
Question 9: In Django URLs, what does path('article/<int:id>/', views.detail) configure?
- A. A route that accepts only float path variables.
- B. A dynamic URL pattern matching an integer id and passing it as an argument to views.detail. β (correct answer)
- C. A route that counts visits to the detail page.
- D. A redirect pattern to external web assets.
Explanation: <int:id> matches a sequence of digits and passes the value to the view variable.
Question 10: What is the purpose of the Django Admin interface?
- A. A command line interface for starting servers.
- B. A built-in, customizable web portal that allows administrators to perform CRUD operations on database models directly. β (correct answer)
- C. A dashboard for monitoring CPU usage.
- D. A firewall control panel.
Explanation: Registering models in admin.py exposes them to a secure admin portal automatically.
Question 11: What is the difference between ModelForm and Form classes in Django?
- A. ModelForm is asynchronous, while Form is synchronous.
- B. ModelForm generates form fields directly from a database model schema, whereas Form requires manual declaration of fields. β (correct answer)
- C. Form works only on databases, while ModelForm works only in memory.
- D. ModelForm is deprecated in Django 4+.
Explanation: ModelForm eliminates redundancy by mapping fields, labels, and validation rules directly from model definitions.
Question 12: How do you run a local development server for a Django project?
- A. python manage.py startserver
- B. python manage.py runserver β (correct answer)
- C. python manage.py host
- D. python manage.py up
Explanation: runserver launches a lightweight local development web server on port 8000.
Question 13: How does Django's middleware framework work?
- A. It compiles template assets into HTML strings.
- B. A framework of hooks that process requests and responses globally before they reach views or return to clients. β (correct answer)
- C. It acts as a database transaction manager.
- D. It encrypts media files.
Explanation: Middlewares execute key tasks like session handling, CSRF check, and authentication globally.
Question 14: What are Django Signals primarily used for?
- A. Routing network traffic between servers.
- B. Allowing decoupled applications to get notified when actions occur elsewhere in the framework (e.g. executing logic post_save of a Model). β (correct answer)
- C. Styling templates dynamically based on user interaction.
- D. Optimizing SQL database queries.
Explanation: Signals allow sender and receiver functions to communicate events without explicit couplings.
Question 15: What is the purpose of the collectstatic command?
- A. Deleting unused database columns.
- B. Gathering all static files (CSS, JS, images) from individual apps into a single directory for production deployment. β (correct answer)
- C. Compiling Python script files.
- D. Clearing browser caches.
Explanation: Production servers serve static files from a single root. collectstatic prepares these directories.
Question 16: In the Django template language, how do you output a variable's value?
- A. {% variable %}
- B. {{ variable }} β (correct answer)
- C. {# variable #}
- D. <% variable %>
Explanation: Double curly braces evaluate and output variables. {% %} is used for template tags (logic).
Question 17: In the Django ORM, what does a Q object allow you to do?
- A. Optimize database cache queries.
- B. Construct complex database queries with OR statements and nested conditions. β (correct answer)
- C. Define custom database index schemas.
- D. Route requests to different databases.
Explanation: Standard filter arguments are chained as AND. Q objects allow complex combinations of AND, OR, and NOT.
Question 18: What does it mean if a Model field has null=True, blank=True?
- A. The field can store empty values in the database, and is optional in forms. β (correct answer)
- B. The field will be deleted automatically.
- C. The field is read-only.
- D. The field holds an integer index value.
Explanation: null affects database columns (allowing NULL values); blank controls form validation (optional field).
Question 19: What is the difference between a Model's save() method and update() in Django?
- A. save() updates only one row, while update() works on lists.
- B. save() instantiates database model lifecycle signals (like pre_save/post_save) and validates model objects, while QuerySet.update() runs direct SQL updates without firing signals. β (correct answer)
- C. save() is slower and deprecated.
- D. update() works only in memory.
Explanation: save() operates on instance levels, triggering logic. update() runs database-level updates directly.
Question 20: Which file matches URL patterns to views inside a Django app?
- A. urls.py β (correct answer)
- B. views.py
- C. routes.py
- D. settings.py
Explanation: urls.py contains urlpatterns lists that route HTTP paths to view functions.
Question 21: How does Django handle database transactions?
- A. It disables transaction logging to speed up queries.
- B. By automatically wrapping HTTP requests in transactions or using the atomic decorator to ensure query groups succeed or roll back. β (correct answer)
- C. It requires manual SQL commits on every query.
- D. It relies entirely on client-side JS validation.
Explanation: django.db.transaction.atomic() guarantees that database edits inside a block are atomic.
Question 22: What is the purpose of the Django custom manager (models.Manager)?
- A. Running command-line scripts.
- B. Modifying the base QuerySet returned by a model (e.g. adding helper query methods or filters like active_users()). β (correct answer)
- C. Managing server memory usage.
- D. Styling admin dashboards.
Explanation: Managers are interfaces for database query operations, letting you define custom model APIs.
Question 23: Which command generates new migration files after modifying models.py?
- A. python manage.py migrate
- B. python manage.py makemigrations β (correct answer)
- C. python manage.py modelchange
- D. python manage.py seed
Explanation: makemigrations inspects models, writing Python delta steps in migrations/ folders.
Question 24: In Django templates, what does the {% extends %} tag do?
- A. Imports another template as a component.
- B. Declares that the current template inherits its layout structure from a base parent template. β (correct answer)
- C. Extends the variable scope of views.
- D. Loops over array elements.
Explanation: extends is the foundation of Django layout inheritance, allowing block overrides.
Question 25: What does the select_related operation do in the Django ORM?
- A. It caches SQL query results in Redis.
- B. It performs a database SQL JOIN, retrieving related foreign key objects in a single database query. β (correct answer)
- C. It limits results to active rows.
- D. It returns query outputs as lists.
Explanation: select_related optimizes database access by loading foreign relations during the main SELECT call.
Question 26: What does it mean that Django is an 'opinionated' framework?
- A. It does not provide database connectivity.
- B. It comes with a pre-configured architecture, directory structures, and tools, promoting best practices. β (correct answer)
- C. It forces you to write code in a single file.
- D. It only works on Linux machines.
Explanation: Django includes built-in solutions (ORM, admin, auth) to accelerate development.
Question 27: How does Django store user session data by default?
- A. In client-side cookies as plain text.
- B. In database tables, sending a session key to the browser cookie for lookup. β (correct answer)
- C. In temporary server RAM files.
- D. On remote CDN locations.
Explanation: Django session middleware saves key-value dictionaries to the database, lookup key via sessionid cookie.
Question 28: What is a Django custom command?
- A. A custom shell script alias.
- B. A custom administrative command that can be run via 'python manage.py command_name'. β (correct answer)
- C. An inline SQL query wrapper.
- D. A template rendering command.
Explanation: Subclassing BaseCommand lets developers write custom system scripts inside management/commands/.
Question 29: What does the models.CASCADE argument on a ForeignKey define?
- A. It speeds up table query times.
- B. It instructs the database to automatically delete the child record if the referenced parent record is deleted. β (correct answer)
- C. It restricts edits to administrative accounts.
- D. It encrypts parent keys.
Explanation: CASCADE maintains referential integrity, deleting dependent records (e.g. posts if user is deleted).
Question 30: Which file is the entry point for running administrative commands in a Django project?
- A. manage.py β (correct answer)
- B. wsgi.py
- C. settings.py
- D. admin.py
Explanation: manage.py handles tasks like starting servers, database migrations, and shell prompts.