Skip to content

Chapter 4 of 8

Views, URLs, and Responses

Django views are Python callables that take an HttpRequest and return an HttpResponse. Function-based views (FBVs) are simple Python functions, while class-based views (CBVs) subclass django.views.View and map HTTP methods to class methods like get() and post(). The CBV is registered in URL configuration by calling its as_view() classmethod. Django's generic class-based views handle common patterns out of the box, including ListView for displaying lists of objects, DetailView for displaying a single object, CreateView, UpdateView, and DeleteView for the corresponding CRUD operations. These views are imported from django.views.generic. For example, ListView accepts a paginate_by attribute to enable pagination, passing page_obj and paginator to the template and reading the page from the ?page= query parameter.

URL routing is configured in urls.py using the urlpatterns list. The path() function maps URL patterns to views, and include() is used to delegate to app-level URL configurations. Path converters capture parts of the URL as typed parameters, with built-in converters including int for integers, str for non-empty strings excluding /, slug for slugs, and uuid for UUIDs. The reverse_lazy function returns a URL string evaluated lazily, which is required when referencing URL reverses in module-level code such as success_url attributes on class-based views, because URLs are not loaded yet at import time. The {% url %} template tag resolves a named URL pattern to its path, accepting either positional or keyword arguments.

The django.shortcuts module provides convenient helpers to keep views concise. render() combines loading a template, populating context, and returning an HttpResponse. redirect() returns an HttpResponseRedirect (302) to a resolved URL, a named URL pattern, or a model instance with get_absolute_url(). get_object_or_404() returns an object or raises Http404, which is preferred over get() in views because Django's 404 handler renders a friendly page. HttpResponse is the base class for all responses, with subclasses including JsonResponse for JSON data, FileResponse for streaming files without loading them fully into memory, and StreamingHttpResponse for streaming iterators like CSV exports. Several view decorators enhance behavior: @require_http_methods rejects unsupported methods with a 405, @login_required restricts access to authenticated users, @cache_page caches the full response, and @condition enables HTTP conditional GETs for efficient 304 responses. The never_cache decorator ensures the response is not cached, while @vary_on_headers appends header names to the Vary response.

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.