Django Views
A view is the heart of every page. It is a Python callable that takes an HttpRequest and returns an HttpResponse. What happens in between is up to you: read the URL or query string, load data from the database, render a template, redirect somewhere else, or return JSON.
# books/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Welcome to the bookshelf!")Your first view
Views are plain functions, so you can call them directly once you have a request. In practice Django calls them for you when a URL matches. Here the test client plays the browser:
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"])
django.setup()
from django.http import HttpResponse
from django.urls import path
from django.test import Client
def index(request):
return HttpResponse("<h1>Welcome to the bookshelf!</h1>")
urls.urlpatterns = [path("", index)]
r = Client().get("/")
print(r.status_code)
print(r["Content-Type"])
print(r.content.decode())200
text/html; charset=utf-8
<h1>Welcome to the bookshelf!</h1>
HttpResponse defaults to text/html; charset=utf-8 and status 200.
The request object
Everything about the incoming request is on request:
| Attribute | Contains |
|---|---|
request.method |
"GET", "POST", "PUT" … |
request.path |
the path, e.g. "/search/" |
request.GET |
query-string parameters (a QueryDict) |
request.POST |
form data from a POST body |
request.headers |
case-insensitive dict of HTTP headers |
request.COOKIES |
cookies sent by the browser |
request.user |
the logged-in user (needs the auth middleware) |
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"])
django.setup()
from django.http import HttpResponse
from django.urls import path
from django.test import Client
def search(request):
term = request.GET.get("q", "")
page = int(request.GET.get("page", 1))
tags = request.GET.getlist("tag")
agent = request.headers.get("User-Agent", "unknown")
text = f"{request.method} {request.path}\nq={term!r} page={page} tags={tags}\nagent={agent}"
return HttpResponse(text, content_type="text/plain")
urls.urlpatterns = [path("search/", search)]
client = Client()
print(client.get("/search/?q=django&tag=web&tag=python").content.decode())
print("---")
print(client.get("/search/", {"page": 3}, headers={"User-Agent": "Firefox"}).content.decode())GET /search/
q='django' page=1 tags=['web', 'python']
agent=unknown
---
GET /search/
q='' page=3 tags=[]
agent=Firefox
Tip: Always read query parameters with
.get(name, default). Indexing (request.GET["q"]) raises an error — and returns a 500 page — when the parameter is missing.
Different kinds of responses
Django provides response subclasses and shortcuts for the common cases:
| Class / shortcut | Use it for |
|---|---|
HttpResponse(content, status=…) |
any text/HTML body |
JsonResponse(dict) |
JSON APIs |
HttpResponseRedirect(url) / redirect(...) |
send the browser elsewhere (302) |
HttpResponseNotFound / raise Http404 |
404 Not Found |
HttpResponseForbidden |
403 Forbidden |
render(request, template, context) |
render a template into a response |
get_object_or_404(Model, ...) |
fetch one row or raise Http404 |
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"])
django.setup()
from django.http import HttpResponse, JsonResponse, Http404
from django.shortcuts import redirect
from django.urls import path
from django.test import Client
BOOKS = {1: "Dune", 2: "Emma"}
def book_json(request, pk):
if pk not in BOOKS:
raise Http404("No such book")
return JsonResponse({"id": pk, "title": BOOKS[pk]})
def old_url(request):
return redirect("/books/1/")
def teapot(request):
return HttpResponse("I'm a teapot", status=418)
urls.urlpatterns = [
path("books/<int:pk>/", book_json),
path("old/", old_url),
path("tea/", teapot),
]
c = Client()
r = c.get("/books/2/")
print(r.status_code, r.json())
print(c.get("/books/9/").status_code)
r = c.get("/old/")
print(r.status_code, r["Location"])
r = c.get("/old/", follow=True)
print(r.status_code, r.json(), r.redirect_chain)
print(c.get("/tea/").status_code)200 {'id': 2, 'title': 'Emma'}
404
302 /books/1/
200 {'id': 1, 'title': 'Dune'} [('/books/1/', 302)]
418
follow=True makes the test client follow redirects just like a browser would, and redirect_chain records each hop.
Handling GET and POST in one view
Function views often branch on request.method. The decorators in django.views.decorators.http reject other methods with 405 Method Not Allowed:
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"])
django.setup()
from django.http import HttpResponse
from django.views.decorators.http import require_http_methods
from django.urls import path
from django.test import Client
NOTES = []
@require_http_methods(["GET", "POST"])
def notes(request):
if request.method == "POST":
NOTES.append(request.POST["text"])
return HttpResponse("saved", status=201)
return HttpResponse(", ".join(NOTES) or "(no notes)")
urls.urlpatterns = [path("notes/", notes)]
c = Client()
print(c.get("/notes/").content.decode())
r = c.post("/notes/", {"text": "buy milk"})
print(r.status_code, r.content.decode())
c.post("/notes/", {"text": "call mom"})
print(c.get("/notes/").content.decode())
print(c.delete("/notes/").status_code)(no notes)
201 saved
buy milk, call mom
405
Note: A real browser form must include a CSRF token for POST requests. The test client skips CSRF checks by default, which keeps these examples short. See Django Security.
Test yourself
What must every Django view return?
- A string
- A dictionary
- An
HttpResponse(or subclass) - A template object
How do you safely read the query parameter q with a default of ""?
- request.GET["q"]
- request.GET.get("q", "")
- request.q
- request.POST.get("q")
Which status code does redirect('/books/1/') produce by default?
- 200
- 301
- 302
- 404