Django Views
Views are the Python functions that receive web requests and return web responses; this lesson covers function-based views, HttpResponse, and the request object.
What Is a View?
In Django, a view is simply a Python function (or callable class) that takes an HttpRequest object as its first argument and returns an HttpResponse object. Django is not opinionated about what happens inside a view - it can query the database, render a template, redirect the user, or return raw JSON. The only contract is: request in, response out.
The HttpRequest Object
Every view receives an HttpRequest instance describing the incoming request. This object carries the HTTP method, submitted form or query-string data, headers, cookies, and - once authentication middleware runs - the logged-in user.
- request.method - the HTTP verb, e.g. 'GET' or 'POST'
- request.GET - a dictionary-like QueryDict of URL query parameters
- request.POST - a QueryDict of submitted form data
- request.path - the path portion of the requested URL
- request.user - the currently authenticated user (or AnonymousUser)
Example 1: A Basic View
# views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("<h1>Welcome to my Django site</h1>")Example 2: Reading Data from the Request
# views.py
from django.http import HttpResponse
def greet(request):
name = request.GET.get("name", "stranger")
if request.method == "GET":
return HttpResponse(f"Hello, {name}! (via GET)")
return HttpResponse("Only GET is supported here.", status=405)Wiring a View to a URL
A view function does nothing until Django's URL dispatcher can find it. Each app typically defines its own urls.py listing path() entries that map a URL pattern to a view, and the project's root urls.py includes those app-level URL configurations.
Example 3: Connecting Views in urls.py
# myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.home, name="home"),
path("greet/", views.greet, name="greet"),
]Exercise: Django Views
What must every Django view function accept as its first parameter?