🌍 Python · subject

Python Django Syllabus

The Django syllabus for Python in full: 4 chapters, 16 topics and 48 sub-topics, every one listed below, plus 55 Django flashcards with answers.

4Chapters
16Topics
48Sub-topics
55Flashcards

Django syllabus: all 4 chapters

Expand any chapter to see its topics and sub-topics.

  1. Introduction to Django

    2 topics
    • What is Django?
      • History and Background
      • Advantages of Django
      • Django vs Other Frameworks
    • Setting up Django
      • Installing Python
      • Installing Django
      • Creating a Django Project
      • Understanding Project Structure
  2. Django Basics

    5 topics
    • Django Apps
      • Creating an App
      • App Structure
    • Django Models
      • Defining Models
      • Model Fields
      • Model Methods
      • Database Migrations
    • Django Views
      • Function-Based Views
      • Class-Based Views
      • Generic Views
    • Django Templates
      • Template Syntax
      • Template Inheritance
      • Template Tags and Filters
    • Django URLs
      • URLconf
      • Path and Re_path
      • Including Other URLconfs
  3. Advanced Django Concepts

    5 topics
    • Django Forms
      • Form Classes
      • Form Validation
      • Model Forms
    • Django Admin
      • Customizing Admin Interface
      • Admin Actions
      • Admin Filters
    • Django Authentication
      • User Model
      • Authentication Views
      • Permissions and Authorization
    • Django Middleware
      • Built-in Middleware
      • Custom Middleware
    • Django REST Framework
      • Serializers
      • Views and ViewSets
      • Routers
      • Authentication and Permissions
  4. Deployment and Maintenance

    4 topics
    • Deployment Options
      • Deploying on Heroku
      • Deploying on AWS
      • Deploying on DigitalOcean
    • Security Best Practices
      • Securing Django Applications
      • Common Security Vulnerabilities
    • Performance Optimization
      • Database Optimization
      • Caching Strategies
      • Asynchronous Tasks
    • Testing in Django
      • Unit Tests
      • Integration Tests
      • Test Coverage

Python Django flashcards — 55 questions with answers

  1. What is Django and what design philosophy does it follow?

    Django is a high-level, open-source Python web framework that encourages rapid development and clean, pragmatic design. It follows the 'batteries-included' philosophy (ships with ORM, admin, auth, etc.) and the DRY (Don't Repeat Yourself) principle.

  2. Which architectural pattern does Django use, and how does it differ from classic MVC?

    Django uses the MVT (Model-View-Template) pattern. Model = data layer, View = business logic, Template = presentation. It maps to MVC where Django's 'View' is MVC's Controller and Django's 'Template' is MVC's View; the framework itself acts as the controller routing requests.

  3. Who maintains Django and under what license is it released?

    Django is maintained by the Django Software Foundation (DSF) and is released under the 3-clause BSD license.

  4. What command starts a new Django project and what command starts a new app?

    django-admin startproject projectname creates a project; python manage.py startapp appname creates an app within the project.

  5. What is the role of manage.py in a Django project?

    manage.py is a command-line utility that lets you interact with the project: running the dev server (runserver), migrations, creating apps, opening the shell, and running tests. It sets DJANGO_SETTINGS_MODULE automatically.

  6. What is the difference between a Django 'project' and a Django 'app'?

    A project is the entire web application and its configuration. An app is a self-contained, reusable module that does one thing (e.g., a blog, polls). A project can contain many apps, and an app can be reused across projects.

  7. How do you run Django's built-in development server, and on what default address/port?

    python manage.py runserver — it serves by default at http://127.0.0.1:8000. You can override with e.g. runserver 0.0.0.0:8080.

  8. Which setting registers an app so Django knows about it, and where does the AppConfig live?

    Add the app (or its AppConfig path, e.g. 'polls.apps.PollsConfig') to INSTALLED_APPS in settings.py. The AppConfig class lives in the app's apps.py.

  9. What is a Django Model and what does each model class typically map to?

    A Django Model is a Python class (subclassing django.db.models.Model) that defines the structure of stored data. Each model class maps to a single database table, and each model attribute (field) maps to a column.

  10. Name five common Django model field types and what they store.

    CharField (short text, needs max_length), TextField (large text), IntegerField (integers), BooleanField (True/False), DateTimeField (date+time). Others: EmailField, ForeignKey, DecimalField.

  11. How do you create a one-to-many relationship between two Django models?

    Use a ForeignKey field on the 'many' side pointing to the 'one' side, e.g. author = models.ForeignKey(Author, on_delete=models.CASCADE). on_delete is required.

  12. What do ManyToManyField and OneToOneField represent in Django models?

    ManyToManyField represents a many-to-many relationship (Django creates a join table automatically). OneToOneField represents a one-to-one relationship, often used to extend another model (e.g. a Profile extending User).

  13. What are the two commands needed to apply model changes to the database in Django?

    python manage.py makemigrations (creates migration files from model changes) and python manage.py migrate (applies those migrations to the database).

  14. What does on_delete=models.CASCADE do on a ForeignKey, and name two alternatives.

    CASCADE deletes the referencing object when the referenced object is deleted. Alternatives: PROTECT (prevents deletion), SET_NULL (sets the FK to NULL, requires null=True), SET_DEFAULT, and DO_NOTHING.

  15. What is the Django ORM and what does QuerySet lazy evaluation mean?

    The ORM (Object-Relational Mapper) lets you query the database using Python objects instead of SQL. QuerySets are lazy: no database query runs until the QuerySet is actually evaluated (iterated, sliced, len(), list(), etc.).

  16. How do you retrieve all objects, filter, and get a single object with the Django ORM?

    Model.objects.all() returns all rows; Model.objects.filter(field=value) returns a filtered QuerySet; Model.objects.get(pk=1) returns a single object (raises DoesNotExist or MultipleObjectsReturned).

  17. What is the purpose of the Meta inner class in a Django model? Give two example options.

    The Meta class configures model-level options (not fields). Examples: ordering = ['-created'] (default ordering), verbose_name, db_table, unique_together / constraints, and abstract = True.

  18. What is a Django View and what are the two main styles of writing views?

    A view is a Python function or class that takes an HttpRequest and returns an HttpResponse. The two styles are Function-Based Views (FBVs) and Class-Based Views (CBVs, which use inheritance and mixins for reusability).

  19. What is the minimal signature of a Django function-based view, and what must it return?

    def my_view(request, *args, **kwargs): — it receives an HttpRequest as the first argument and must return an HttpResponse object (or subclass like JsonResponse, or raise Http404).

  20. Name three commonly used Django generic class-based views and their purpose.

    ListView (display a list of objects), DetailView (display a single object), CreateView/UpdateView/DeleteView (CRUD forms), TemplateView (render a template), RedirectView (redirect).

Show the other 35 Django flashcards
  1. What shortcut functions does Django provide for rendering templates and handling missing objects?

    render(request, template, context) renders a template to an HttpResponse; get_object_or_404() fetches an object or raises Http404; redirect() returns an HttpResponseRedirect; render also handles context processors.

  2. What is a Django Template and which two constructs does the Django Template Language (DTL) use?

    A template is a text file (usually HTML) with DTL syntax for dynamic content. DTL uses {{ variable }} for outputting values and {% tag %} for logic tags (loops, conditionals, blocks, includes).

  3. What are template filters in Django and how are they applied? Give two examples.

    Filters transform variable output using the pipe | syntax: {{ value|filter:arg }}. Examples: {{ name|upper }}, {{ list|length }}, {{ text|truncatewords:10 }}, {{ date|date:'Y-m-d' }}, {{ value|default:'N/A' }}.

  4. How does template inheritance work in Django with block and extends?

    A base template defines {% block name %}...{% endblock %} regions. Child templates start with {% extends 'base.html' %} and override blocks. {% include %} pulls in another template fragment.

  5. What is the difference between {% url %} tag usage and hardcoding URLs in templates?

    {% url 'name' arg %} reverses a named URL pattern into its path, so URLs stay correct even if the URLconf changes. Hardcoding paths is brittle and breaks when routes change.

  6. What is a URLconf in Django and which file typically holds the root URL patterns?

    A URLconf is a mapping of URL patterns to views, defined as a urlpatterns list. The root URLconf is set by ROOT_URLCONF in settings (usually the project's urls.py).

  7. What do path() and re_path() do in Django URL configuration?

    path() defines a URL pattern using simple route syntax with converters (e.g. '<int:id>/'). re_path() defines a pattern using a regular expression for more complex matching.

  8. How do you capture a typed integer parameter from a URL using path converters?

    Use a path converter inside angle brackets: path('post/<int:id>/', views.detail) captures an integer and passes id to the view. Other converters: <str:>, <slug:>, <uuid:>, <path:>.

  9. What is the purpose of include() in Django URL configuration?

    include() lets the root URLconf delegate a set of URLs to an app's own urls.py, e.g. path('blog/', include('blog.urls')). This keeps apps modular and reusable.

  10. What does naming a URL pattern and using app_namespace enable in Django?

    Naming a pattern (name='detail') lets you reverse it with reverse() or {% url %} instead of hardcoding paths. app_name / namespaces (e.g. 'blog:detail') disambiguate names across multiple apps.

  11. What is a Django Form and what are the two base classes for forms?

    A Form handles rendering HTML inputs, validating submitted data, and cleaning/converting it to Python types. The base classes are forms.Form (manual fields) and forms.ModelForm (auto-builds fields from a model).

  12. 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).

  13. 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.

  14. 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.

  15. 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.

  16. 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.

  17. 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.

  18. 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.

  19. 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).

  20. 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.

  21. 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).

  22. 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.

  23. 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.

  24. 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).

  25. 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).

  26. 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.

  27. 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.

  28. 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.

  29. 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.

  30. 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.

  31. 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.

  32. 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.

  33. 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.

  34. 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.

  35. 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.

Python Django FAQ

What is in the Python Django syllabus?

Python Django is split into 4 chapters: Introduction to Django, Django Basics, Advanced Django Concepts and Deployment and Maintenance. Together they contain 16 topics and 48 sub-topics.

How many chapters are in Python Django?

4 chapters, containing 16 topics and 48 sub-topics. The largest chapter is Django Basics, with 5 topics.

Are there flashcards for Python Django?

Yes — a 55-card Django deck, printed in full in the flashcards section of this page and available in the Examius app with spaced repetition. The free plan covers one exam of your choice, including its flashcards; Examius Pro, a one-time purchase, unlocks every other exam and deck.