Django Django 2 — Questions and Answers
Question 1: Which Django command applies pending database migrations to the database?
- python manage.py migrate (Correct answer)
- python manage.py makemigrations
- python manage.py syncdb
- python manage.py runserver
Correct answer: python manage.py migrate
The migrate command applies migration files to the database schema.
Question 2: In a Django model, which field type is best for storing a large block of multi-line text?
- TextField (Correct answer)
- CharField
- EmailField
- SlugField
Correct answer: TextField
TextField stores unbounded multi-line text, unlike CharField which requires max_length.
Question 3: What does the Django ORM method filter() return?
- A QuerySet (Correct answer)
- A single model instance
- A Python list
- A dictionary
Correct answer: A QuerySet
filter() returns a lazy QuerySet that can be further chained or evaluated.
Question 4: Which decorator restricts a view to logged-in users in Django?
- @login_required (Correct answer)
- @require_auth
- @user_required
- @authenticated
Correct answer: @login_required
@login_required from django.contrib.auth.decorators redirects anonymous users to the login page.
Question 5: What is the purpose of Django's {% csrf_token %} template tag?
- Protect POST forms from cross-site request forgery (Correct answer)
- Cache the rendered template
- Generate a random session ID
- Escape HTML output
Correct answer: Protect POST forms from cross-site request forgery
It inserts a hidden token that Django validates to prevent CSRF attacks on form submissions.
Question 6: Which setting controls whether detailed error pages are shown to users?
- DEBUG (Correct answer)
- ALLOWED_HOSTS
- SECRET_KEY
- INSTALLED_APPS
Correct answer: DEBUG
DEBUG should be False in production to avoid leaking sensitive error details.
Question 7: How do you retrieve a single object or raise a 404 in a Django view?
- get_object_or_404() (Correct answer)
- Model.objects.get_or_404()
- find_or_fail()
- Model.objects.first()
Correct answer: get_object_or_404()
get_object_or_404() from django.shortcuts returns the object or raises Http404 if not found.
Which Django command applies pending database migrations to the database?