Python Django Framework Quiz

Python
0 Passed
0% acceptance

A comprehensive 60-question quiz covering the Django web framework, from project structure and models to views, templates, and advanced configuration.

60 Questions
~120 minutes
1

Question 1

In Django, what is the fundamental difference between a 'Project' and an 'App'?

A
They are synonyms.
B
A Project is a container for configuration and apps; an App is a web application that does something.
C
A Project handles the database; an App handles the frontend.
D
An App contains multiple Projects.
2

Question 2

What is the primary purpose of the `manage.py` file created in every Django project?

A
It contains the database settings.
B
It is a command-line utility that lets you interact with this Django project.
C
It handles the URL routing.
D
It is the entry point for the WSGI server.
3

Question 3

Which file in a Django app directory is used to configure app-specific settings, such as the app's name?

A
models.py
B
config.py
C
apps.py
D
admin.py
4

Question 4

Where does Django store the history of changes made to your database models?

A
In the `db.sqlite3` file directly.
B
In the `migrations` directory within each app.
C
In the `settings.py` file.
D
In the `__pycache__` folder.
5

Question 5

What is the role of `wsgi.py` in a Django project?

A
It handles WebSocket connections.
B
It is the entry point for WSGI-compatible web servers to serve your project.
C
It manages static files.
D
It defines the URL patterns.
6

Question 6

You want to create a new app named 'blog' within your project. Which command do you run?

A
python manage.py startapp blog
B
python manage.py createapp blog
C
django-admin new app blog
D
python manage.py makeapp blog
7

Question 7

How do you capture an integer parameter named 'id' from a URL path?

javascript

urlpatterns = [
    path('post/____/', views.post_detail),
]
                
A
<id>
B
<int:id>
C
{id:int}
D
(?P<id>[0-9]+)
8

Question 8

What is the purpose of the `include()` function in `urls.py`?

javascript

from django.urls import path, include
urlpatterns = [
    path('blog/', include('blog.urls')),
]
                
A
It imports the view functions directly.
B
It references another URLconf module, delegating handling of that path prefix to it.
C
It includes HTML templates.
D
It redirects the user.
9

Question 9

Why is it recommended to name your URLs, e.g., `path(..., name='home')`?

A
It is required for the view to work.
B
It allows you to refer to the URL globally (e.g., in templates or redirects) without hardcoding the path.
C
It improves SEO.
D
It secures the URL.
10

Question 10

What is the difference between `path()` and `re_path()`?

A
`path()` uses simple path converters; `re_path()` uses regular expressions.
B
`path()` is for GET requests; `re_path()` is for POST.
C
`re_path()` is deprecated.
D
They are identical.
11

Question 11

How do you namespace URLs for a specific app so that `post_detail` in 'blog' doesn't conflict with `post_detail` in 'news'?

A
Set `app_name = 'blog'` in the app's `urls.py`.
B
Rename the views.
C
Use `namespace='blog'` in `settings.py`.
D
It is handled automatically.
12

Question 12

Which function is used in Python code (e.g., in views) to obtain the URL path from a view name?

A
get_url()
B
redirect()
C
reverse()
D
resolve()
13

Question 13

What is the first argument passed to every view function?

javascript

def my_view(____):
    return HttpResponse("Hello")
                
A
self
B
request
C
response
D
context
14

Question 14

Which shortcut function loads a template, fills it with context, and returns an `HttpResponse` object?

A
template.load()
B
render()
C
render_to_response()
D
respond()
15

Question 15

What does `get_object_or_404(MyModel, pk=1)` do?

A
It returns `None` if the object is not found.
B
It raises a standard Python `KeyError`.
C
It calls `MyModel.objects.get()` and raises `Http404` if the object does not exist.
D
It redirects to the 404 page.
16

Question 16

In a Class-Based View (CBV), which method handles GET requests?

A
handle_get()
B
get()
C
dispatch()
D
do_get()
17

Question 17

How do you return a JSON response from a view?

A
return HttpResponse(json.dumps(data))
B
return JsonResponse(data)
C
return render(data, 'json')
D
Both A and B work, but B is preferred.
18

Question 18

What is the purpose of the `context` dictionary passed to `render`?

A
It configures the database settings.
B
It maps variable names to values so they can be accessed inside the template.
C
It stores session data.
D
It defines URL patterns.
19

Question 19

In Django templates, what syntax is used to output the value of a variable?

A
{% variable %}
B
{{ variable }}
C
${variable}
D
<%= variable %>
20

Question 20

How do you enable template inheritance?

javascript

<!-- base.html -->
<html><body>{% block content %}{% endblock %}</body></html>

<!-- child.html -->
{% ____ 'base.html' %}
{% block content %}Hi{% endblock %}
                
A
include
B
extends
C
inherit
D
import
21

Question 21

Which filter formats a date object?

javascript

{{ my_date|____:"Y-m-d" }}
                
A
format
B
date
C
time
D
strftime
22

Question 22

What does the `{% csrf_token %}` tag do?

A
It authenticates the user.
B
It generates a hidden input field with a token to protect against Cross-Site Request Forgery.
C
It encrypts the form data.
D
It validates the form fields.
23

Question 23

How do you load static files (like CSS) in a template?

javascript

{% ____ %}
<link rel="stylesheet" href="{% static 'style.css' %}">
                
A
load static
B
load staticfiles
C
import static
D
static_url
24

Question 24

What happens if you try to access a dictionary key that doesn't exist in a template variable, e.g., `{{ my_dict.missing_key }}`?

A
It raises a KeyError.
B
It prints 'None'.
C
It fails silently and prints nothing (empty string).
D
It crashes the server.
25

Question 25

To define a database model, which class must you inherit from?

A
django.db.Model
B
django.models.Model
C
django.orm.Entity
D
object
26

Question 26

Which field type is best suited for a long text entry (like a blog post body)?

A
CharField
B
TextField
C
StringField
D
BlobField
27

Question 27

What does `on_delete=models.CASCADE` do in a ForeignKey?

A
It prevents the referenced object from being deleted.
B
It deletes the object containing the ForeignKey if the referenced object is deleted.
C
It sets the ForeignKey to NULL.
D
It does nothing.
28

Question 28

Where do you define model metadata like `verbose_name` or `ordering`?

javascript

class MyModel(models.Model):
    name = models.CharField(max_length=100)
    
    class ____:
        ordering = ['name']
                
A
Config
B
Meta
C
Settings
D
Info
29

Question 29

Why should you define the `__str__` method in your model?

A
It is required for the database.
B
It provides a human-readable string representation of the object, used in the Admin panel and debugging.
C
It is used for encryption.
D
It defines the primary key.
30

Question 30

Which command applies the pending migrations to the database?

A
python manage.py makemigrations
B
python manage.py migrate
C
python manage.py sync_db
D
python manage.py apply
31

Question 31

How do you register a model with the admin site?

javascript

# admin.py
from .models import Post
____(Post)
                
A
admin.register
B
admin.site.register
C
admin.add_model
D
site.register
32

Question 32

Which `ModelAdmin` attribute controls the columns shown in the list view of objects?

A
columns
B
list_display
C
fields
D
display_fields
33

Question 33

How do you add a sidebar filter to the admin list view?

A
list_filter = ('field_name',)
B
filter_fields = ('field_name',)
C
sidebar = True
D
search_fields = ('field_name',)
34

Question 34

What command creates a user who can log in to the admin site?

A
python manage.py createadmin
B
python manage.py createsuperuser
C
python manage.py adduser --admin
D
python manage.py init_admin
35

Question 35

Can you group fields into sections on the admin edit page?

A
No, fields are always listed alphabetically.
B
Yes, using the `fieldsets` attribute.
C
Yes, using `groups`.
D
Only with custom HTML templates.
36

Question 36

How do you make a field read-only in the admin interface?

A
readonly_fields = ('field_name',)
B
editable = False in the model
C
Both A and B
D
It is not possible.
37

Question 37

What is Middleware in Django?

A
The database driver.
B
A framework of hooks into Django's request/response processing.
C
The frontend JavaScript.
D
The template engine.
38

Question 38

In which order is middleware processed during a Request?

A
Top to Bottom (as defined in settings).
B
Bottom to Top.
C
Random order.
D
Alphabetical order.
39

Question 39

Which middleware is responsible for associating a user with a request (i.e., `request.user`)?

A
SecurityMiddleware
B
SessionMiddleware
C
AuthenticationMiddleware
D
CommonMiddleware
40

Question 40

If you write a custom middleware class, which method is mandatory to implement?

A
__init__ and __call__
B
process_request
C
process_view
D
handle()
41

Question 41

What happens if a middleware's `process_request` method returns an `HttpResponse`?

A
Django continues to the next middleware.
B
Django continues to the view.
C
Django stops processing the request and immediately returns that response (skipping views and other middleware).
D
It raises an error.
42

Question 42

Where do you activate middleware?

A
In `urls.py`.
B
In the `MIDDLEWARE` list in `settings.py`.
C
In `wsgi.py`.
D
In the database.
43

Question 43

Why must `DEBUG = True` never be used in production?

A
It makes the site slower.
B
It exposes sensitive configuration data and source code snippets in error pages.
C
It prevents the database from saving.
D
It disables static files.
44

Question 44

What is the purpose of `ALLOWED_HOSTS`?

A
It lists the users allowed to log in.
B
It lists the domain names/IPs that this Django site can serve.
C
It lists the database hosts.
D
It lists allowed API clients.
45

Question 45

Does the order of apps in `INSTALLED_APPS` matter?

A
No, never.
B
Yes, for things like template overriding and static file discovery.
C
Only for the admin app.
D
Yes, but only alphabetically.
46

Question 46

Which setting defines the database engine and credentials?

A
DB_CONFIG
B
DATABASES
C
SQL_ALCHEMY
D
DATA_SOURCE
47

Question 47

What is `SECRET_KEY` used for?

A
Cryptographic signing (sessions, CSRF tokens, password reset tokens).
B
Database password.
C
Admin login.
D
API authentication.
48

Question 48

What does `ROOT_URLCONF` point to?

A
The root directory of the project.
B
The Python module that contains the main URL patterns.
C
The homepage view.
D
The static files URL.
49

Question 49

What is the difference between `STATIC_URL` and `STATIC_ROOT`?

A
`STATIC_URL` is the URL prefix (e.g., /static/); `STATIC_ROOT` is the folder where `collectstatic` gathers files for production.
B
They are the same.
C
`STATIC_ROOT` is for development; `STATIC_URL` is for production.
D
`STATIC_URL` is the file path; `STATIC_ROOT` is the web address.
50

Question 50

Where does Django look for static files by default?

A
Only in `STATIC_ROOT`.
B
In the `static` directory of each installed app.
C
Anywhere on the disk.
D
In the database.
51

Question 51

What does the command `python manage.py collectstatic` do?

A
It downloads static files from the internet.
B
It copies static files from all apps and `STATICFILES_DIRS` into `STATIC_ROOT`.
C
It deletes static files.
D
It compiles SCSS to CSS.
52

Question 52

Does Django serve static files in production automatically?

A
Yes, always.
B
No, Django is not designed to serve static files efficiently in production; you should use Nginx/Apache/WhiteNoise.
C
Yes, if DEBUG=False.
D
Only images.
53

Question 53

What is the difference between Static files and Media files in Django terminology?

A
Static files are app assets (CSS/JS); Media files are user-uploaded content.
B
Static files are images; Media files are videos.
C
They are the same.
D
Media files are for admins only.
54

Question 54

How do you serve user-uploaded media files during development?

javascript

# urls.py
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=____)
                
A
settings.STATIC_ROOT
B
settings.MEDIA_ROOT
C
settings.BASE_DIR
D
settings.UPLOAD_DIR
55

Question 55

What is the main advantage of using `ModelForm` over a standard `Form`?

A
It is faster.
B
It automatically generates form fields based on a model definition and handles saving to the database.
C
It looks better.
D
It uses AJAX.
56

Question 56

Which method checks if the form data is valid?

A
form.check()
B
form.validate()
C
form.is_valid()
D
form.save()
57

Question 57

Where is the sanitized data stored after calling `is_valid()`?

A
form.data
B
form.cleaned_data
C
form.validated_data
D
request.POST
58

Question 58

How do you render a form in a template as a list of paragraphs?

javascript

<form method="post">
    {{ form.____ }}
    <button>Submit</button>
</form>
                
A
as_p
B
as_list
C
paragraphs
D
render
59

Question 59

What happens if you forget `{% csrf_token %}` in a POST form?

A
Nothing, it works fine.
B
Django returns a 403 Forbidden error.
C
The form submits but data is lost.
D
It becomes a GET request.
60

Question 60

How do you add custom validation for a specific field, e.g., 'email'?

A
Define a method `clean_email(self)` in the form class.
B
Use `validate_email` in the view.
C
Override the `save` method.
D
It requires a custom field type.

QUIZZES IN Python