Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 77 ยท URLs and Views

Function-Based Views

Write Django function-based views: return HttpResponse and JsonResponse, raise Http404, redirect, use render and get_object_or_404, and restrict HTTP methods.

A view is the Python code that answers a request. The simplest kind of view is an ordinary function: it receives an HttpRequest, does some work and returns an HttpResponse. These function-based views (FBVs) are the easiest way to start with Django, and many experienced developers keep using them for anything that is not a standard "list, create, edit, delete" page.

In this lesson you will write views that return plain text, HTML templates and JSON, send redirects, signal errors with Http404, use the shortcut functions render, redirect and get_object_or_404, and restrict which HTTP methods a view accepts with decorators. Everything runs live with Django's test client.

The shape of a view

Every function-based view follows the same contract:

Python
def view_name(request, *args, **kwargs):
    ...
    return HttpResponse(...)
  1. The first parameter is the HttpRequest (conventionally called request).
  2. Any values captured by the URL pattern arrive as additional arguments. path("hello/<str:name>/", greet) calls greet(request, name="...").
  3. The function returns an HttpResponse, or raises an exception that Django turns into one.

That is all the framework asks. A view may be defined anywhere importable, but by convention lives in an app's views.py.

flowchart TD
    A["view(request, ...)"] --> B{"What happened?"}
    B -->|"normal result"| C["return HttpResponse / JsonResponse / render(...)"]
    B -->|"send the user elsewhere"| D["return redirect(...)"]
    B -->|"object does not exist"| E["raise Http404 / get_object_or_404"]
    B -->|"not allowed"| F["raise PermissionDenied / 405 via decorator"]

A view either returns a response or raises an exception that Django converts into the matching error response.

Returning responses

HttpResponse is the base class. Pass it a string (or bytes), and optionally status and content_type. Django adds sensible headers (Content-Type, Content-Length) for you. For JSON, JsonResponse serializes a dictionary and sets Content-Type: application/json; for HTML pages you will almost always use render(), which fills a template with context data and wraps the result in an HttpResponse.

Redirects and errors are responses too:

  • redirect("name", ...) returns a redirect response. It accepts a URL name (it calls reverse() for you), a model instance (it uses get_absolute_url()) or a literal URL. By default it sends a 302 (temporary) redirect; pass permanent=True for 301.
  • raise Http404("message") stops the view and produces the site's 404 page. You do not return it; you raise it, so it can be thrown from deep inside helper code.
  • For other statuses, create HttpResponse(..., status=...) or use a subclass such as HttpResponseBadRequest (400) or HttpResponseForbidden (403).
Python Plain text, templates, JSON, errors and redirects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A few things to read off the output. render() produced text/html automatically, JsonResponse produced application/json, and the missing product turned into a 404 even though the code never built a 404 response by hand. The two redirects show Location headers built by reverse(), so renaming the URLs would not break them. Using the test client's .json() helper parses a JSON response back into Python.

With DEBUG = False (as in these examples) a Http404 produces Django's plain "Not Found" page. With DEBUG = True, Django shows a detailed technical page that lists the URL patterns it tried, which is helpful in development and must never be shown in production. Customizing error pages is the topic of Error Pages and Exceptions.

The shortcuts

django.shortcuts collects helpers that cover the most common view steps:

Shortcut What it does
render(request, template, context) Renders a template and returns an HttpResponse.
redirect(to, *args, **kwargs) Returns a redirect to a URL name, model or URL.
get_object_or_404(Model, **lookups) Returns one object, or raises Http404 if there is none. Also accepts a QuerySet.
get_list_or_404(Model, **lookups) Returns a list, or raises Http404 if it is empty.

get_object_or_404() replaces a try/except around Model.objects.get() that you would otherwise repeat in every detail view. Without it, an unknown id would raise DoesNotExist and show a 500 error, which is wrong: a missing record is a client problem, not a server bug, and search engines should see a 404.

Restricting HTTP methods

A view that creates data must not run for a GET request, otherwise a crawler or a prefetching browser could trigger it just by following a link. Django ships decorators in django.views.decorators.http:

  • @require_GET, @require_POST, @require_safe (GET and HEAD),
  • @require_http_methods(["GET", "POST"]) for any list.

When the method is not allowed, the decorator returns a 405 Method Not Allowed response with an Allow header that lists the permitted methods. Decorators wrap the view function and can be stacked; they run from the outermost (top) inward. Your own decorators should use functools.wraps so the wrapped view keeps its __name__ and docstring, as you saw in the Python lesson on decorators.

The example below uses a real in-memory database. It combines get_object_or_404, get_list_or_404, a custom decorator and the method decorators, and uses the status code 204 No Content for a delete.

Python Method decorators, get_object_or_404 and a custom decorator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Follow the sequence in the output. The detail view found note 1 and attached our custom header; note 99 produced a 404 via get_object_or_404; a POST to the read-only URL got 405 with Allow: GET; the create view accepted a POST and answered 201 Created; and after the delete, get_list_or_404 turned the empty table into a 404.

The test client skips CSRF checks by default, which is why the POST above works without a token. In a real browser, POST views behind the default middleware require a CSRF token unless you use @csrf_exempt (rarely a good idea). Forms and CSRF are covered in Handling Forms in Views.

When function-based views shine

Function-based views are explicit: everything the view does is visible in one function, and there is no inheritance to trace. They are a good fit for custom logic, one-off pages, JSON endpoints and anything where the standard CRUD patterns do not apply. Class-based views, covered in the next lessons, remove repetition from standard patterns, but they are not "better"; choose whichever makes the code clearest.

Some habits that keep views healthy:

  • Keep views thin. Move business rules into models, managers or plain service functions, so they can be tested without HTTP.
  • Return the right status code: 201 for created, 204 for no content, 400 for bad input, 404 for missing, 403 for forbidden.
  • Use redirect() after a successful POST instead of rendering a page directly, so a refresh does not resubmit the form.
  • Don't build URLs by hand; use reverse() or redirect() with names.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must every Django view return, or raise?

    Django's handler expects a response object. Exceptions like Http404 are caught and turned into the matching error response.
  2. 2. What does get_object_or_404(Note, pk=99) do when no such note exists?

    The shortcut wraps get() and converts a missing record into Http404, which is the correct HTTP outcome for an unknown id.
  3. 3. A view decorated with @require_POST receives a GET request. What happens?

    The decorator short-circuits before your function runs and answers 405, listing the allowed methods in the Allow header.
  4. 4. What does redirect('home') return by default?

    redirect() reverses the name and returns a 302 unless you pass permanent=True.

Summary

  • A function-based view takes an HttpRequest (plus URL arguments) and returns an HttpResponse or raises an exception that becomes one.
  • Use HttpResponse for text, JsonResponse for JSON and render() for templates; set status for other codes.
  • redirect() builds redirects from URL names or models; Http404 and get_object_or_404 signal missing resources.
  • require_GET, require_POST and require_http_methods restrict methods and answer 405 with an Allow header.
  • Custom decorators should use functools.wraps; stack decorators from the outside in.
  • Keep views thin, return accurate status codes and redirect after successful POSTs.

Next lesson: Query Strings, Forms and Request Data.