🎓 A1Learner
🔍
0 of 50 lessons completed

Django View Arguments

A view argument is a value from the address that a view receives. The converter names the argument, and the view uses it.

Write the view

This view takes a name after request. It returns a greeting that holds the name.

def greet(request, name):
    return HttpResponse(f"Hello, {name}!")

Greet Sana

The test client asks for Sana. The view prints a greeting for her.

print(client.get("/hello/Sana/").content.decode())

Greet Omar

The same view answers a new name. The greeting changes with the argument.

print(client.get("/hello/Omar/").content.decode())

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 greet(request, name):
    return HttpResponse(f"Hello, {name}!")


urlpatterns = [path("hello/<str:name>/", greet)]

from django.test import Client

client = Client()
print(client.get("/hello/Sana/").content.decode())
print(client.get("/hello/Omar/").content.decode())

Key points

  • A view argument comes from a converter in the route string.
  • The argument name in the view must match the converter name.
  • The view takes the argument after request.
  • The view can use the argument to build its page.
  • One view can answer many addresses, one per argument value.

In this example, the setup lines configure Django. The greet view takes a name argument after request. It returns a greeting that holds the name. The pattern catches text as name. The test client tries two names and shows both greetings.

Note

The argument arrives with the type its converter gives it.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Where does a view argument come from?