Writing Views
A view is a Python function (or class) that receives a web request and returns a web response. Views are where your site's logic lives: they read what the user asked for, fetch data and decide what to send back.
Your first view
Every function-based view takes an HttpRequest object as its first argument, conventionally called request, and must return an HttpResponse.
events/views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("<h1>Campus Events</h1><p>Karibu! Find out what's happening on campus.</p>")
A view does nothing until a URL points to it. Create events/urls.py and connect it to the project's URLconf (the next page, URL Routing, explains this in detail):
events/urls.py
from django.urls import path
from . import views
app_name = "events"
urlpatterns = [
path("", views.home, name="home"),
]
campus/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("events/", include("events.urls")),
]
Run the server and visit http://127.0.0.1:8000/events/. You'll see the heading and welcome message.
The request object
Django fills request with everything it knows about the incoming request. The attributes you'll use most:
| Attribute | What it holds | Example |
|---|---|---|
request.method | The HTTP method as a string | "GET" or "POST" |
request.GET | Query-string values from the URL | /events/?q=fair gives request.GET["q"] == "fair" |
request.POST | Submitted form data | Values from a sign-up form |
request.path | The path without the domain | "/events/" |
request.user | The logged-in user, or an anonymous user | request.user.is_authenticated |
request.headers | HTTP headers, case-insensitive | request.headers["User-Agent"] |
Returning HTML with render()
Writing HTML inside Python strings quickly becomes painful. The render() shortcut loads a template, fills it with a context dictionary and returns an HttpResponse. We'll use a Python list as pretend data until we build a real database model on the Models page.
events/views.py
from django.http import Http404
from django.shortcuts import render
EVENTS = [
{"id": 1, "title": "Freshers' Welcome Night", "venue": "Main Hall", "capacity": 300},
{"id": 2, "title": "Campus Hackathon", "venue": "ICT Lab 2", "capacity": 60},
{"id": 3, "title": "Career Fair", "venue": "Main Hall", "capacity": 500},
]
def event_list(request):
query = request.GET.get("q", "")
events = [e for e in EVENTS if query.lower() in e["title"].lower()]
context = {"events": events, "query": query}
return render(request, "events/event_list.html", context)
def event_detail(request, pk):
for event in EVENTS:
if event["id"] == pk:
return render(request, "events/event_detail.html", {"event": event})
raise Http404("No event with that ID.")
A few things to notice:
request.GET.get("q", "")reads the search box safely. Using.get()with a default avoids aKeyErrorwhen the user didn't search. Visiting/events/?q=fairwould show only the Career Fair.event_detailtakes a second argument,pk, which comes from the URL (for example/events/2/).- Raising
Http404makes Django return a "Page not found" response with status code 404.
Update events/urls.py so the list is at /events/ and each event has its own address:
events/urls.py
urlpatterns = [
path("", views.event_list, name="event_list"),
path("<int:pk>/", views.event_detail, name="event_detail"),
]
Other useful responses and shortcuts
events/views.py
from django.http import JsonResponse
from django.shortcuts import redirect
def event_count(request):
# Useful for a mobile app or JavaScript widget
return JsonResponse({"count": len(EVENTS)})
def old_events_page(request):
# Send visitors from an old address to the new one
return redirect("events:event_list")
Visiting event_count returns this JSON:
| Tool | Use it to |
|---|---|
HttpResponse | Return plain text or a small piece of HTML |
render() | Return a page built from a template |
redirect() | Send the browser to another URL, view name or object |
JsonResponse | Return JSON data |
Http404 / get_object_or_404() | Return "Page not found" when something doesn't exist |
Once you have a database model, get_object_or_404(Event, pk=pk) replaces the whole loop in event_detail with one line.
Handling GET and POST in one view
Many views behave differently depending on the method: GET shows a page or form, POST processes submitted data. The usual shape is:
def contact(request):
if request.method == "POST":
# read request.POST, save something, then redirect
return redirect("events:event_list")
# GET: just show the page
return render(request, "events/contact.html")
You'll fill this pattern in properly on the Django Forms page.
Forgetting to return the response. A view that ends without returning anything gives the error "The view events.views.event_list didn't return an HttpResponse object. It returned None instead." Check every branch of your if statements returns something.
Changing data (saving, deleting, sending money) in response to a GET request. Search engines and browser previews follow links automatically, so any link that deletes something could be triggered by accident. Only change data on POST.
Key points
- A view takes a
requestand returns a response. - Use
request.GETfor URL query values andrequest.POSTfor form data. render()combines a template and a context dictionary into an HTML response.redirect(),JsonResponseandHttp404cover most other needs.- Always return a response, and only change data on POST.
Tip: use the ← and → keys to move between pages.
