Your First Django View
A view is a Python function that answers a web request. It returns a page as its answer.
Write the view
This function takes a request and returns a page. The page holds one line of text.
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django!")Ask for the page
The test client asks for / and shows the page that comes back.
client = Client()
print(client.get("/").content.decode())Check the status code
A status code is a number that says how the request went. The number 200 means the page arrived.
print(client.get("/").status_code)Example
import django
from django.conf import settings
settings.configure(DEBUG=True, SECRET_KEY="key", ROOT_URLCONF=__name__, ALLOWED_HOSTS=["*"])
django.setup()
from django.http import HttpResponse
from django.urls import path
def home(request):
return HttpResponse("Hello, Django!")
urlpatterns = [path("", home)]
from django.test import Client
client = Client()
print(client.get("/").content.decode())
print(client.get("/").status_code)Key points
- A view function is a plain Python function that takes a request.
- HttpResponse builds a page from text.
- A view returns an HttpResponse.
- The view runs each time its address is asked for.
- Use the test client to check a view while writing it.
In this example, the setup lines configure Django. The home view returns Hello, Django! as a page. The pattern list pairs the empty address with home. The test client asks for / and shows the page. The closing print shows the status code, 200.
Note
The first view argument is always named request by habit.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does a view return?