HttpResponse & Shortcuts

Return responses with HttpResponse, render, redirect and get_object_or_404.

Views must return an HttpResponse (or raise an exception). Django provides handy shortcuts:

  • HttpResponse(text) — a plain response.
  • render(request, template, context) — render a template to a response.
  • redirect(to) — send a 302 redirect.
  • get_object_or_404(Model, pk=...) — fetch or raise a 404.

Example

Example · python
from django.shortcuts import render, redirect, get_object_or_404
from .models import Post

def detail(request, id):
    post = get_object_or_404(Post, pk=id)
    return render(request, "blog/detail.html", {"post": post})

def go_home(request):
    return redirect("index")

When to use it

  • A developer returns a plain-text health-check response from a /ping/ endpoint using HttpResponse.
  • A developer uses HttpResponseRedirect after a successful form submission to follow the Post/Redirect/Get pattern.
  • A developer returns an HttpResponseForbidden when a user tries to access a resource they don't own.

More examples

Return plain text response

Returns a plain-text response with a custom content type using HttpResponse.

Example · python
from django.http import HttpResponse

def ping(request):
    return HttpResponse("pong", content_type="text/plain")

Redirect after POST

Redirects the user after a successful POST to prevent duplicate form submission on refresh.

Example · python
from django.http import HttpResponseRedirect
from django.urls import reverse

def submit(request):
    if request.method == "POST":
        # ... save data ...
        return HttpResponseRedirect(reverse("success"))
    return render(request, "form.html")

Custom status codes

Shows how to return HTTP responses with non-200 status codes using the status parameter.

Example · python
from django.http import HttpResponse

def created(request):
    return HttpResponse("Created", status=201)

def not_found(request):
    return HttpResponse("Not found", status=404)

Discussion

  • Be the first to comment on this lesson.