Build Python web applications with routes, views, models and templates.
Before starting: Python functions, classes, environments, HTML, and HTTP.
Practice project: Build a study log with model validation and request tests.
1. Django Introduction, Environment & Architecture
- Django Introduction, History & The "Batteries-Included" Philosophy
- Django Environment Setup: Virtualenv, pip & Development Server
Read the example and try it
Use the interpreter inside the project environment to check the installed framework. Then run the project checks beside manage.py.
Terminal in an activated Django project, beside manage.py.
python -m django --version python manage.py checkPrint the interpreter path before starting a project.
In the same shell used to start Django, run python -c "import sys,django; print(sys.executable,django.get_version())".
Expected result
An interpreter path and a Django version appear. The path should be in the intended environment or explicitly selected interpreter; it varies by machine. - Django Project Anatomy: manage.py, settings.py, urls.py & wsgi.py
Read the example and try it
A project chooses settings and the root URL configuration. Inspect the active configuration using the project's shell.
Run in python manage.py shell.
from django.conf import settings print(settings.ROOT_URLCONF)Trace a URL from project settings to its URL patterns.
ROOT_URLCONF points to campus.urls. That file includes bookings.urls at rooms/, where <int:pk>/ maps to detail.
Expected result
GET /rooms/7/ resolves to detail with pk=7. A route missing from both lists returns 404. - Django Apps Architecture: Projects vs Apps & Modular Design
Read the example and try it
An app packages a particular feature such as a room directory. Inspect the registry to see which installed apps Django loaded.
Run in python manage.py shell.
from django.apps import apps print([app.label for app in apps.get_app_configs()])Sketch a project containing separate bookings and payments apps.
Create a campus project with bookings and payments installed as separate apps.
Expected result
Both app labels appear in the application registry. Each app can own its own models, migrations and URLs within the project. - The Request-Response Lifecycle: WSGI/ASGI, Middleware, URLconf & MVT
Read the example and try it
A view turns the matched request into a response. Test the view with a request factory before adding a URL pattern.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.http import HttpResponse from django.test import RequestFactory def board(request): return HttpResponse("Next stop: Lake") print(board(RequestFactory().get("/board/")).content.decode())Trace one request through routing, a view and a response.
Map /hello/ to a view returning HttpResponse("Lab open").
Expected result
GET /hello/ → resolver selects view → view returns status 200 with body Lab open.
2. Django Models, Field Types & Migrations
- Django Models, Fields & Database Abstraction Layer
Read the example and try it
A model class describes the fields of a database record. Add this class to an installed app, then create and apply its migration.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.db import models class Room(models.Model): label = models.CharField(max_length=40) seats = models.PositiveIntegerField()Compare creating an object in memory with inserting it.
Create Room(name="Lab") without saving. Start with an empty table and an automatic primary key.
Expected result
Row count is 0 before save. After save it is 1 and the instance has a primary key. Constructing the Python object alone does not insert it. - Django Field Types, Choices, Defaults & Validators
Read the example and try it
A validator checks a value during validation. Directly saving a model does not automatically call full_clean.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.core.validators import MinValueValidator from django.db import models class Trip(models.Model): seats = models.IntegerField(validators=[MinValueValidator(1)])Choose form and database settings for an optional date.
Model an optional booked_on date that accepts an empty form and stores SQL NULL.
Expected result
DateField(blank=True,null=True). The empty form validates and the saved field is None when read back. - Model Relationships: ForeignKey, OneToOneField & ManyToManyField
Read the example and try it
A booking refers to one room while a room can have many bookings. PROTECT stops deletion of a referenced room.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.db import models class Booking(models.Model): room = models.ForeignKey("Room", on_delete=models.PROTECT, related_name="bookings")Draw two orders pointing to the same customer.
One customer C7 owns orders A and B. Use a foreign key on Order.
Expected result
Both orders refer to C7. The customer's reverse collection contains A and B; only one customer record is needed. - Database Migrations Workflow: makemigrations, migrate & showmigrations
Read the example and try it
A migration records a change in schema. Inspect the planned actions before applying changes to a shared database.
Terminal beside manage.py. Use a disposable practice project.
python manage.py makemigrations python manage.py migrate --planSeparate creating a migration file from applying it.
Starting with a fresh local project, add a field and run makemigrations, then migrate.
Expected result
First a migration file appears. The database schema changes only after applying the migration. showmigrations marks the applied migration [X]. - Model Meta Options, Abstract Base Classes & Model Inheritance
Read the example and try it
A model's Meta class can supply a default ordering. Add a tie-breaker if multiple records can have the same name.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
class Meta: ordering = ["label", "pk"]Contrast inherited fields with a separate related record.
Define an abstract base with a created field, then a concrete Booking inheriting it. Compare with an explicit customer foreign key.
Expected result
Booking has its own created column and no abstract-base table. The customer is a separate row linked by a key.
3. Django ORM, QuerySets & Optimization
- Django QuerySets, CRUD Operations & Field Lookups
Read the example and try it
A lookup narrows a queryset before it is evaluated. This query selects rooms with capacity at least eight.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
rooms = Room.objects.filter(seats__gte=8).order_by("seats") print(list(rooms.values_list("label", flat=True)))Construct a filter and identify the operation that evaluates it.
Use rooms Lab=8 and Hall=12. Construct Room.objects.filter(seats__gte=10) and evaluate it with list().
Expected result
Constructing the filter does not fetch its rows. The evaluated result contains Hall only. - Advanced ORM: Q Objects, F Expressions & Dynamic Queries
Read the example and try it
Q expressions combine filter conditions. F expressions compare values stored in different columns of the same row.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.db.models import F, Q available = Trip.objects.filter(Q(capacity__gt=F("booked")) | Q(waitlist=True))Increase a counter with an expression that reads its stored value.
Persist count=4 and update it through F("count")+1. Read back from the database.
Expected result
5. Refresh an already-loaded object before displaying the new value. - Aggregations, Annotations & Grouping (Count, Sum, Avg)
Read the example and try it
An annotation adds a calculated field per row. Count related bookings rather than loading each room's entire booking list.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.db.models import Count print(list(Room.objects.annotate(total=Count("bookings")).values("label","total")))Count bookings per room and then count all bookings.
Create two bookings for Lab and one for Hall.
Expected result
Per-room counts: Lab=2 and Hall=1. The total booking count is 3. Sort explicitly if you want a particular display order. - Database Optimization: select_related & prefetch_related
Read the example and try it
Fetch the single related room along with each booking. This avoids an extra room query each time the loop reads its label.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
for booking in Booking.objects.select_related("room"): print(booking.pk, booking.room.label)Choose a loading strategy for an order's customer and its items.
A list page needs each order's single customer and all its items.
Expected result
select_related("customer") can join the customer in the order query. prefetch_related("items") fetches and associates the collection in another query. Iteration over already-prefetched items avoids a query per order. - Raw SQL Queries, Database Routers & Atomic Transactions
Read the example and try it
Keep related writes in one transaction. If a later operation raises an exception, the database can roll back the earlier change.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.db import transaction with transaction.atomic(): room = Room.objects.select_for_update().get(pk=7) if room.seats < 1: raise ValueError("Room full") room.seats -= 1 room.save(update_fields=["seats"])Show what rolls back when the second of two writes fails.
Inside transaction.atomic, insert a booking then violate a unique constraint. Catch the exception outside the block.
Expected result
The first insert is rolled back too. The count of new bookings from that block is zero; records committed earlier remain.
4. URL Routing, Views & HTTP Handling
- URL Dispatcher, Path Converters & Named Routes
Read the example and try it
A path converter checks the shape of the URL and passes a Python value to the view. Here seat_id arrives as an integer.
Project urls.py. Import the local views module as views.
from django.urls import path urlpatterns = [path("seats/<int:seat_id>/", views.seat, name="seat")]Match a numeric path and a nonnumeric path against one route.
Use path("rooms/<int:pk>/",detail) with no other matching route.
Expected result
/rooms/7/ supplies integer 7. /rooms/abc/ does not match and returns 404. - Function-Based Views (FBVs): HttpRequest, HttpResponse & JsonResponse
Read the example and try it
A function-based view receives the request first. Return a response object even for a tiny text result.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.http import HttpResponse def seat(request, seat_id): return HttpResponse(f"Seat {seat_id}", content_type="text/plain")Write a view returning a plain-text greeting.
Return a text/plain response containing Hello, Lab.
Expected result
Status 200; content type text/plain; response body Hello, Lab. - Class-Based Views (CBVs): Introduction to View & TemplateView
Read the example and try it
A class-based view dispatches a GET request to its get method. Register the class using as_view in the URL configuration.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.http import JsonResponse from django.views import View class Capacity(View): def get(self, request): return JsonResponse({"seats": 4})Trace GET and POST requests to separate methods.
Define get() returning read and post() returning saved on the same View; use a local test client.
Expected result
GET returns read and POST returns saved. Route the class through as_view(). Real browser POSTs must satisfy any configured CSRF check. - Django Shortcuts: render, redirect, get_object_or_404
Read the example and try it
Look up the room before rendering its details. A missing key should give the visitor a 404 response.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.shortcuts import get_object_or_404, render def detail(request, pk): room = get_object_or_404(Room, pk=pk) return render(request, "rooms/detail.html", {"room": room})Describe the responses for an existing and missing record.
Use get_object_or_404 for Lab's existing primary key, then for an absent key.
Expected result
Existing record → 200 with Lab's details. Absent key → Http404, rendered as HTTP 404. - Handling Query Parameters, POST Payloads & HTTP Headers
Read the example and try it
A repeated query parameter can have several values. Use getlist when the learner may choose more than one day.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
def chosen_days(request): return JsonResponse({"days":request.GET.getlist("day")})Separate a URL filter from a submitted form field.
POST to /search/?floor=2 with a form field room=Lab.
Expected result
request.GET["floor"] is "2"; request.POST["room"] is "Lab". Both values are strings in this fixture.
5. Generic Class-Based Views & Mixins
- Display Generic CBVs: ListView & DetailView
Read the example and try it
A list view needs a queryset and a template. Pagination limits how many room records are sent on each page.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.views.generic import ListView class RoomList(ListView): model = Room paginate_by = 10 template_name = "rooms/list.html"Pair a list URL and a detail URL with their view types.
List all rooms at /rooms/ and show room 7 at /rooms/7/.
Expected result
The first URL uses ListView and yields a collection. The second uses DetailView and returns one permitted object or 404. - Editing Generic CBVs: CreateView, UpdateView & DeleteView
Read the example and try it
Whitelist the editable fields when generating a creation form. Apply the project's permission checks before exposing a write view.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.contrib.auth.mixins import PermissionRequiredMixin from django.views.generic import CreateView class AddRoom(PermissionRequiredMixin, CreateView): permission_required = "rooms.add_room" model = Room fields = ["label","seats"] success_url = "/rooms/"Sketch the confirmation page and its write request.
Open a delete confirmation for Lab, then submit its valid protected form.
Expected result
GET leaves the row present. Authorized POST deletes it and normally redirects to a success URL. A missing or invalid CSRF token is rejected when enforcement applies. - Working with FormView & Custom Form Workflows
Read the example and try it
A FormView calls form_valid after successful validation. Use cleaned_data when reading the submitted values.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.views.generic.edit import FormView class RoomSearch(FormView): form_class = SearchForm template_name = "rooms/search.html" success_url = "/rooms/" def form_valid(self, form): self.request.session["room_query"] = form.cleaned_data["query"] return super().form_valid(form)Trace valid and invalid form submissions.
Submit seats=3 and seats=bad to a FormView with a required IntegerField.
Expected result
Valid input reaches form_valid and the configured success redirect. Invalid input redisplays a bound form with an error and produces no write. - CBV Mixins: LoginRequiredMixin, UserPassesTestMixin & Custom Mixins
Read the example and try it
A sign-in check identifies the user. Scope the queryset as well when different users own different bookings.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import ListView class MyBookings(LoginRequiredMixin, ListView): def get_queryset(self): return Booking.objects.filter(owner=self.request.user)Specify separate checks for login and ownership.
Alice owns booking A. Bob is signed in but owns booking B. Request A as each user.
Expected result
Alice may edit A. Bob receives the configured denial, for example 404 from an owner-filtered queryset. A login check alone would incorrectly allow Bob through. - Overriding CBV Methods: get_queryset, get_context_data & form_valid
Read the example and try it
Extend the context returned by the parent view. Replacing it entirely would lose values supplied by the generic view.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["page_label"] = "Room directory" return contextDesign two users' lists and keep their rows separate.
Give Alice rows A1,A2 and Bob row B1. Filter get_queryset by request.user.
Expected result
Alice sees only A1,A2 and Bob sees only B1. Test both responses for absence of the other user's identifiers.
6. Django Template Engine (DTE)
- DTE Architecture, Template Variables, Tags & Comments
Read the example and try it
A template can iterate through records supplied by the view. Give the learner an empty state when the queryset has no rows.
Django template receiving a rooms queryset.
<ul>{% for room in rooms %}<li>{{ room.label }}</li>{% empty %}<li>No rooms yet</li>{% endfor %}</ul>Render a name containing an angle bracket with autoescaping on.
Use room.name="<Lab>" in normal Django text interpolation with autoescaping.
Expected result
HTML source contains <Lab>. A browser displays the literal text <Lab> without creating a Lab element. - Template Inheritance: {% extends %}, {% block %} & {% include %}
Read the example and try it
A child template fills a named block in its parent. Other blocks keep the parent layout.
Child template beside a base.html containing a content block.
{% extends "base.html" %} {% block content %}<h1>Room directory</h1>{% endblock %}Make two pages share one layout and override their headings.
A base template defines block heading and contains a common footer. Two child pages set heading to Rooms and Bookings.
Expected result
Each page shows its own heading and the same footer. A change to the base footer affects both. - Built-in Filters & Tags (date, truncatewords, default, forloop)
Read the example and try it
A filter can change the display without changing stored data. The default_if_none filter supplies text only for a null value.
Django template receiving room in its context.
<p>Capacity: {{ room.seats|default_if_none:"Unknown" }}</p>Display an item's count with the correct singular or plural label.
Use count and the pluralize filter to print the label for 1 and 2 rooms.
Expected result
1 room; 2 rooms. - Custom Template Tags, Simple Tags & Custom Filters
Read the example and try it
Register a filter in an installed template-tag library. This one returns ordinary text so normal escaping still applies.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django import template register = template.Library() @register.filter def seat_label(number): return f"Seat {number}"Register a small formatting filter and show its use.
Create a registered filter room_label that trims and uppercases input. Load its library and format " lab ".
Expected result
LAB. Loading the registered library makes the filter available in that template. - Static Files & Media Assets: {% static %}, STATIC_ROOT & MEDIA_ROOT
Read the example and try it
Use the static tag for a stylesheet shipped with the app. Uploaded files follow the configured media storage instead.
Django template in an app configured for static files.
{% load static %} <link rel="stylesheet" href="{% static 'rooms/board.css' %}">Separate a logo shipped with the app from an uploaded avatar.
Ship logo.svg with the application and upload avatar.png during a request.
Expected result
The logo resolves through static storage. The avatar comes from the configured media storage. A later collectstatic run is not an upload backup.
7. Forms, ModelForms & File Handling
- Standard Django Forms (forms.Form): Fields, Widgets & Validation
Read the example and try it
A form field converts and validates submitted text. Try both a positive count and zero, then check the errors.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django import forms class SeatForm(forms.Form): count = forms.IntegerField(min_value=1, max_value=12) print(SeatForm({"count":"0"}).is_valid())Submit a bad numeric value to a form with an integer field.
Submit "eight" to forms.IntegerField(min_value=1).
Expected result
is_valid() is False and the field has an invalid-number error. Calling code must not use an unvalidated value. - ModelForms: Binding Models to HTML Forms Automatically
Read the example and try it
A ModelForm can expose a small subset of a model. Keeping the field list explicit protects future internal fields from accidental editing.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.forms import ModelForm class RoomForm(ModelForm): class Meta: model = Room fields = ["label","seats"]Exclude an owner or approval field from an editing form.
Allow only name and capacity in a room ModelForm. Add owner and approved to the submitted input.
Expected result
The generated form exposes name and capacity only. Extra keys do not update protected fields. Assign ownership on the server. - Advanced Form Validation: clean_<field>() & clean() Methods
Read the example and try it
A field-cleaning method can transform valid input and reject blank labels after trimming. Return the cleaned value.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django import forms class LabelForm(forms.Form): label = forms.CharField() def clean_label(self): return self.cleaned_data["label"].strip().upper()Check that an end date follows the start date.
Require end date strictly later than start date. Test Jan 2→Jan 1 and Jan 2→Jan 3 of the same year.
Expected result
First submission has a form error; second validates. Only compare dates after both fields have cleaned successfully. - Formsets & Inline Formsets for Multi-Record Manipulation
Read the example and try it
A formset repeats the same form for several rows. Include the management form in the template so Django knows the submitted row count.
Django form template receiving a formset.
{{ formset.management_form }} {% for form in formset %}<fieldset>{{ form.as_p }}</fieldset>{% endfor %}Explain what to investigate if management data is missing.
Submit two forms without the management fields, then with matching prefix, TOTAL_FORMS=2 and INITIAL_FORMS=0.
Expected result
Without valid management data the formset fails validation. With matching counts and valid member values it validates as two forms. - Handling File & Image Uploads, FileField, ImageField & Storage
Read the example and try it
Bind uploaded files as well as text fields. The browser's form must use multipart encoding, and the form must validate the upload.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
def bind_badge(request): return BadgeForm(request.POST, request.FILES)Trace one multipart upload into storage.
Send a small file named hello.txt containing Lab via a multipart POST. Bind request.POST and request.FILES.
Expected result
The upload appears under its form field in request.FILES. After saving, read back Lab through the storage backend. The storage may rename the file.
8. Admin Interface, Auth & Session Management
- Django Admin Customization: ModelAdmin, list_display & search_fields
Read the example and try it
A ModelAdmin defines how staff browse records. Search fields and list columns can use different parts of the model.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.contrib import admin @admin.register(Room) class RoomAdmin(admin.ModelAdmin): list_display = ["label","seats"] search_fields = ["label"]Choose three useful columns for a bookings admin list.
For a booking admin list choose room, learner and starts_at from existing model fields.
Expected result
The list displays those three columns for each booking. This setting changes the staff listing and does not add database fields. - Advanced Admin: TabularInline, Custom Admin Actions & list_filter
Read the example and try it
An inline edits related records on a parent's admin page. Set extra to zero when staff usually inspect existing bookings.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.contrib import admin class BookingInline(admin.TabularInline): model = Booking extra = 0Show which line items belong on an order's edit page.
Order A has lines A1,A2 and order B has B1. Open A's admin edit page with an inline.
Expected result
Only A1 and A2 are initially displayed for A. B1 must not appear in A's editable inline rows. - Django Authentication System: User, authenticate(), login() & logout()
Read the example and try it
Use the framework's authentication API so its configured backends check the credentials. Handle an unsuccessful attempt explicitly.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.contrib.auth import authenticate def accepted(request, name, password): return authenticate(request, username=name, password=password) is not NoneDescribe the difference between setting and checking a password.
Set a test user's password to demo with set_password, save, then call check_password for demo and bad.
Expected result
True then False. The stored password is a hash representation, not the literal demo. - Permissions, User Groups & Access Decorators (@login_required, @permission_required)
Read the example and try it
Check the required permission on the server before returning protected information. A disabled browser button alone cannot enforce the rule.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.contrib.auth.decorators import permission_required @permission_required("rooms.view_booking", raise_exception=True) def totals(request): return JsonResponse({"count":Booking.objects.count()})Design a denied case for a signed-in reader.
Give a signed-in reader view permission but withhold change permission. Attempt the protected edit.
Expected result
The write is denied, for example HTTP 403 with raise_exception=True, and the original record is unchanged. - Session Framework, Cookie Management & Messages Framework
Read the example and try it
Session storage can remember a non-sensitive preference across requests. Supply a default for a new browser session.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
def room_size(request): size = request.session.get("text_size", "normal") return JsonResponse({"text_size":size})Compare tamper detection with confidentiality.
Use a signed-cookie session for the sample value room=Lab. Tamper with one signed byte.
Expected result
The original cookie can be verified and read. The altered cookie fails signature validation. Signing does not hide Lab from the cookie holder.
9. Middleware, Signals, Caching & Testing
- Custom Middleware Architecture: process_request, __call__ & Hooks
Read the example and try it
Middleware can add a header after the downstream view returns. Keep the response object supplied by that view.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
def study_header(get_response): def middleware(request): response = get_response(request) response["X-Study-Area"] = "rooms" return response return middlewareDraw the inward and outward paths through two layers.
Order two middleware layers O then I around a successful view.
Expected result
O request → I request → view → I response → O response. - Django Signals: post_save, pre_delete & Custom Signal Receivers
Read the example and try it
A post-save signal can schedule work after the surrounding transaction commits. That avoids reporting a record that was rolled back.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.db import transaction from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=Room) def room_saved(sender, instance, **kwargs): transaction.on_commit(lambda: print("Saved room", instance.pk))Describe what happens if an order write rolls back.
Register an on_commit callback for an order inside an atomic block, then roll the block back.
Expected result
No committed order row and zero callback invocations. On successful commit the callback runs once in this simple fixture. - Django Caching: Per-View, Template Fragment & Low-Level Cache API
Read the example and try it
A cache entry needs a key and an expiry. Include the room ID so records from different rooms cannot overwrite each other.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.core.cache import cache cache.set("room:7:capacity", 12, timeout=60) print(cache.get("room:7:capacity"))Design distinct cache keys for two personal dashboards.
Use user IDs 7 and 9 in dashboard cache keys.
Expected result
dashboard:7 and dashboard:9 are distinct. Writing Alice's result for key 7 cannot supply Bob's result under key 9. - Unit & Integration Testing: TestCase, RequestFactory & Test Client
Read the example and try it
Test a route through the client to exercise routing and response generation together. This example assumes the named room endpoint returns JSON.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.test import TestCase class BoardTests(TestCase): def test_capacity(self): response = self.client.get("/capacity/") self.assertEqual(response.status_code, 200) self.assertEqual(response.json()["seats"], 4)Assert a successful detail request and a missing one.
Use the test client for an existing room and an absent one on the same detail route.
Expected result
Assert 200 and the expected room name for the first; assert 404 for the second. - Sending Emails, Asynchronous Tasks & Background Jobs
Read the example and try it
Schedule a task after saving the booking transaction. Pass an ID rather than serialising the full model object.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from django.db import transaction def queue_receipt(booking): transaction.on_commit(lambda: send_receipt.delay(booking.pk))Trace when a new order ID becomes safe to send to a worker.
Queue a notification for a new order using on_commit; replace the worker with a local recording callback.
Expected result
Before commit the recording list is empty. After commit it contains the order ID once. A rolled-back insert enqueues nothing.
10. Django REST Framework, Security & Production Deployment
- Django REST Framework (DRF): Serializers & APIView Basics
Read the example and try it
A serializer validates input before exposing typed values to the API view. Check errors before accessing validated_data.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from rest_framework import serializers class SeatRequest(serializers.Serializer): seats = serializers.IntegerField(min_value=1) s = SeatRequest(data={"seats":"3"}) if s.is_valid(): print(s.validated_data)Test a valid JSON document with a missing required field.
A serializer requires name. Submit valid JSON {}.
Expected result
Parsing succeeds. Serializer validation fails with an error for name; an API view using raise_exception=True returns 400. No room is created. - DRF ViewSets, ModelViewSet & DefaultRouter for RESTful APIs
Read the example and try it
A read-only viewset can publish list and detail routes without adding write actions. Register it with the project's router.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from rest_framework import viewsets class RoomsViewSet(viewsets.ReadOnlyModelViewSet): queryset = Room.objects.all() serializer_class = RoomSerializerMatch list and detail routes to two actions.
Register a rooms viewset with list and retrieve actions.
Expected result
GET /rooms/ calls list. GET /rooms/7/ calls retrieve for pk=7. Registration by itself does not add write access. - DRF Authentication (Token, JWT) & Custom API Permissions
Read the example and try it
A valid token identifies a user. Filter the records even after the permission class accepts the request.
Django project fragment. Use the matching model, form, view or template in an installed app. The example names refer to records in your practice project.
from rest_framework.permissions import IsAuthenticated class MyTrips(viewsets.ReadOnlyModelViewSet): permission_classes = [IsAuthenticated] serializer_class = BookingSerializer def get_queryset(self): return Booking.objects.filter(owner=self.request.user)Outline a request with a valid identity and denied access.
An authenticated user lacks the permission to edit room 7. Try PATCH with valid authentication.
Expected result
Permission denied, normally HTTP 403 for this authenticated case. The room stays unchanged. - Django Web Security: CSRF, XSS, Clickjacking & Security Middleware
Read the example and try it
Include the CSRF token in a same-site POST form. The receiving view still validates the data and checks permission to change the booking.
Django template served by a view with CSRF middleware enabled.
<form method="post">{% csrf_token %}{{ form.as_p }}<button>Book seat</button></form>Match CSRF, HTML escaping and bound parameters to separate threats.
Threats: forged form POST, HTML tag in an untrusted name, quote in a database filter.
Expected result
Use CSRF protection, context-appropriate autoescaping and bound query values respectively. Each addresses a different boundary. - Production Deployment: WSGI/ASGI, Gunicorn, Nginx, WhiteNoise & Docker
Read the example and try it
Run deployment checks against the actual production settings module. Review each warning before routing live requests to the app.
Terminal beside manage.py; substitute your deployment settings module.
python manage.py check --deploy --settings=study.settings.productionList two measurements to watch while adjusting workers.
Send the same 80 requests at concurrency 8 to one worker and then to two. Use the same endpoint, warm up each worker first, and distribute requests across the active workers. Repeat before choosing a configuration.
Expected result
For each run, record successful requests, errors, requests per second, the 95th-percentile response time, and memory per worker. Compare runs against your latency and memory limits. Counts and timings depend on the endpoint and machine.
Validate input and encode PHP HTML output
Validation and output encoding solve different problems. Validation decides whether a value is acceptable for the application. Encoding preserves text when it is inserted into HTML. htmlspecialchars is appropriate for the HTML text context below; it is not a universal encoder for JavaScript, CSS, or URLs. Prepared database statements are a separate defense for SQL values.
PHP 8; Django and ASP.NET learners should use their template system equivalents
<?php
$name = $_GET["name"] ?? "Student";
if (!is_string($name) || strlen($name) > 80) {
http_response_code(400);
exit("Invalid name");
}
?>
<p>Hello, <?= htmlspecialchars($name, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8") ?></p>Check the output
For name=Asha the browser displays: Hello, Asha. Markup supplied as a name is displayed as text in this context.Explain why putting the same value inside a script block needs different handling. Never infer server security merely because PHP source is not normally sent to the browser.
Open the Django learning path on DevStudyHub · Play coding games on this blog
No comments:
Post a Comment
Please do not enter any spam link in the comment box.