🌍 Python · flashcards
Python Django Flashcards
55 question-and-answer cards covering Django as it is examined in Python. 24 of them are printed below, taken from across the deck — no signup, no paywall on the preview.
24 sample cards from the Django deck
Sampled from the end of the deck, so these are different cards from the ones shown on the syllabus page.
What is the key advantage of a Django ModelForm over a plain Form?
A ModelForm automatically generates form fields from a model's fields and provides a .save() method to create/update model instances directly, reducing boilerplate. You configure it via its inner Meta class (model and fields).
What is the standard pattern for processing a form in a Django view (the POST/GET branch)?
If request.method == 'POST': bind data form = MyForm(request.POST); if form.is_valid(): use form.cleaned_data (or form.save()) then redirect. Else render an unbound form = MyForm() for GET requests.
What does form.is_valid() do and where do cleaned values end up?
is_valid() runs validation on bound data and returns True/False. On success, cleaned and type-converted values are stored in form.cleaned_data; errors are stored in form.errors.
How do you add custom validation for a single field in a Django form?
Define a method named clean_<fieldname>(self) on the form that returns the cleaned value or raises forms.ValidationError. For cross-field validation, override the clean() method.
Why does Django require a CSRF token in POST forms, and how do you include it in a template?
To prevent Cross-Site Request Forgery attacks, Django validates a CSRF token on unsafe requests. Include {% csrf_token %} inside the <form> tag; CsrfViewMiddleware enforces it.
What is the Django Admin and what makes it appear?
The Django Admin is an automatically generated, model-driven web interface for managing site data (CRUD). It comes from the django.contrib.admin app and is available at /admin/ once configured and a superuser exists.
How do you register a model with the Django admin and create a superuser?
Register in admin.py with admin.site.register(MyModel) or the @admin.register(MyModel) decorator. Create a superuser with python manage.py createsuperuser.
Name three ModelAdmin options used to customize the admin list/detail views.
list_display (columns shown in the list), list_filter (sidebar filters), search_fields (search box), ordering, list_editable, fieldsets/fields, readonly_fields, and inlines (related models).
What does Django's authentication system provide out of the box?
The django.contrib.auth app provides the User model, password hashing, login/logout, sessions, permissions, and groups. Helpers include authenticate(), login(), logout(), and the @login_required decorator.
What is the difference between authentication and authorization in Django, and how does Django handle each?
Authentication verifies who a user is (authenticate()/login(), the User model). Authorization decides what they can do (permissions, groups, has_perm(), @permission_required, is_staff/is_superuser flags).
How do you restrict a view to logged-in users in Django (FBV and CBV)?
FBV: apply the @login_required decorator. CBV: inherit from LoginRequiredMixin. Unauthenticated users are redirected to settings.LOGIN_URL.
How are passwords stored in Django, and why is that important?
Django never stores plaintext passwords; it stores salted, hashed passwords using configurable hashers (default PBKDF2 with SHA256, plus Argon2/bcrypt options). This protects credentials if the database is compromised.
What is Django Middleware and how is it ordered?
Middleware is a framework of hooks that process every request/response globally. It is a list in the MIDDLEWARE setting. Requests pass top-to-bottom on the way in and bottom-to-top on the way out (like an onion).
Name three built-in Django middleware classes and what they do.
SecurityMiddleware (security headers/HTTPS), SessionMiddleware (session handling), CommonMiddleware (URL normalization), CsrfViewMiddleware (CSRF protection), AuthenticationMiddleware (attaches request.user).
What methods can a custom Django middleware define, and what is the basic new-style structure?
New-style middleware is a callable class: __init__(self, get_response) and __call__(self, request) which calls get_response(request). Optional hooks: process_view, process_exception, process_template_response.
What is Django REST Framework (DRF) and what core component replaces forms for APIs?
DRF is a third-party toolkit for building Web APIs on top of Django. Serializers (replacing forms) convert complex types like querysets/model instances to JSON and validate incoming data; ModelSerializer auto-builds fields from a model.
In DRF, what is the difference between APIView, generic views, and ViewSets?
APIView is the base class (manual HTTP method handlers). Generic views (e.g. ListCreateAPIView) provide common CRUD patterns via mixins. ViewSets group related actions (list/create/retrieve/update/destroy) and pair with routers for automatic URL routing.
What are common deployment options for Django and why is runserver not used in production?
Deploy with a WSGI/ASGI server (Gunicorn, uWSGI, Daphne/Uvicorn) behind a reverse proxy (Nginx) — or use PaaS like Heroku, Railway, or containers (Docker). The runserver dev server is single-threaded, insecure, and not built for production load.
What key production settings must change before deploying Django, and how are static files served?
Set DEBUG = False, configure ALLOWED_HOSTS, use a secret SECRET_KEY from the environment, and a production database. Run collectstatic to gather static files (served by Nginx or WhiteNoise), and serve via WSGI/ASGI.
List four Django security best practices for production.
Keep DEBUG=False and SECRET_KEY secret; set ALLOWED_HOSTS; enforce HTTPS (SECURE_SSL_REDIRECT, HSTS, secure cookies); keep CSRF/XSS protections and {% csrf_token %}; use the ORM/parameterized queries to avoid SQL injection; keep Django updated. Run manage.py check --deploy.
Name four Django performance optimization techniques.
Use select_related (FK joins) and prefetch_related (M2M/reverse) to avoid N+1 queries; add database indexes; cache with the caching framework (Redis/Memcached); use .only()/.defer() and pagination; avoid query-in-loop; enable connection pooling/persistent connections.
What is the N+1 query problem in Django and how do select_related and prefetch_related fix it?
N+1 occurs when accessing related objects in a loop triggers one extra query per row. select_related fixes it for ForeignKey/OneToOne via a SQL JOIN (single query); prefetch_related fixes ManyToMany/reverse relations with a separate batched lookup.
What testing tools does Django provide and what base class do you use for tests?
Django includes a test framework built on Python's unittest. Subclass django.test.TestCase, which wraps each test in a database transaction (rolled back after) and provides a test Client to simulate requests. Run with python manage.py test.
What is the Django test Client used for, and what does setUp/setUpTestData provide?
The test Client simulates HTTP requests (client.get/post) to test views, status codes, redirects, and context without a real server. setUp() runs before each test method; setUpTestData() creates shared read-only fixtures once per class for speed.
What this deck covers
The Django deck follows the Python Django syllabus — 4 chapters and 16 topics — so questions land on material that is genuinely examinable rather than trivia around it. That works out to roughly 13.8 cards per chapter.
Answers are written to be recallable, not just readable — averaging about 214 characters, which is long enough to carry the reasoning and short enough to say out loud.
A deck like this earns its keep on the second and third pass. Read the syllabus first so you know the shape of the subject, then use the cards to find the specific facts that have not stuck.
Django flashcards FAQ
How many Django flashcards are in this Python deck?
55 cards. This page previews 24 of them, sampled evenly across the deck so you can judge the difficulty before installing anything.
Are these Python flashcards free?
Yes. The preview here is free to read with no signup, and the full 55-card deck is free inside the Examius app.
What do the Django cards cover?
They follow the Python Django syllabus — 4 chapters and 16 topics — so the questions track what is actually examinable.
How should I use these flashcards?
Read the syllabus first so you know the shape of the subject, then drill the deck. Examius schedules each card with spaced repetition, so cards you keep missing come back sooner and ones you know drift further apart.