Skip to content

Chapter 8 of 8

DRF, Signals, Testing, and More

Django REST Framework (DRF) is a powerful toolkit for building Web APIs on top of Django. Its key components include Serializers for converting models to and from JSON, ViewSets for grouping related API views, Routers for auto-generating URL patterns, multiple authentication options including token, session, and JWT, and a browsable API web interface for testing. A serializer converts complex data types like models and querysets to native Python types for JSON rendering and vice versa. The Serializer class requires manual field definition and custom create() and update() methods, while the ModelSerializer automatically generates fields from a model and provides default implementations, also auto-generating validators based on model constraints.

Signals allow decoupled components to be notified when certain actions occur. Common built-in signals include pre_save and post_save for before and after model saves, pre_delete and post_delete for deletions, and request_started and request_finished for request lifecycle events. Signals are connected using the @receiver(post_save, sender=MyModel) decorator. Custom signals can be created using django.dispatch.Signal(), sent with the send() method, and received by functions decorated with @receiver. This pattern is useful for triggering side effects like sending confirmation emails or invalidating caches when model events occur.

Django's testing framework extends Python's unittest with TestCase, and tests are run with python manage.py test. The test Client simulates HTTP requests without a running server, handling cookies, sessions, and redirects automatically. The Django cache framework supports various backends including Redis, Memcached, locmem, db, and filebased, configured via the CACHES setting. The low-level cache API uses cache.set, cache.get, cache.get_or_set, and cache.delete, with None as the timeout meaning cache forever. The @cache_page decorator caches entire view responses, while the {% cache %} template tag caches fragments. Cache invalidation patterns include deleting keys after saves, using versioned keys, and clearing cache through signals. Sessions store arbitrary data per visitor on the server side, accessible via request.session, with multiple backends available. Management commands extend Django's CLI by placing a Command class in myapp/management/commands/, accepting arguments through add_arguments(). The send_mail() helper and EmailMessage class provide email functionality, with the console backend printing emails to stdout during development and the locmem backend capturing them in mail.outbox for testing. Internationalization uses gettext_lazy to mark translatable strings, with makemessages and compilemessages commands generating .po and .mo files. Specialized fields like JSONField store arbitrary JSON with key lookups for queries, while UUIDField stores 128-bit UUIDs, often paired with <uuid:id> path converters for type-safe routing. The auto_now and auto_now_add options on DateTimeField automatically track creation and modification timestamps, and timezone.now() should be preferred over datetime.now() when USE_TZ is enabled.

All chapters
  1. 1Django Fundamentals and Project Layout
  2. 2Models, ORM, and Migrations
  3. 3Advanced Querying and Optimization
  4. 4Views, URLs, and Responses
  5. 5Templates and the Presentation Layer
  6. 6Forms, Admin, and Authentication
  7. 7Middleware, Security, and File Handling
  8. 8DRF, Signals, Testing, and More

Drill it

Reading is not remembering. These come from the Django Framework deck:

Q

What is Django?

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It follows the MTV (Model-Template-View) architectura...

Q

What is the Django MTV pattern?

MTV stands for Model-Template-View:Model – defines data structure and database schemaTemplate – handles the presentation layer (HTML)View – contains business lo...

Q

How do you create a new Django project?

Use the command:django-admin startproject myprojectThis generates the project directory with settings.py, urls.py, wsgi.py, asgi.py, and manage.py.

Q

How do you create a new Django app?

Run:python manage.py startapp myappThen add 'myapp' to the INSTALLED_APPS list in settings.py to register it with the project.