Michal Rosenbaum
Michal Rosenbaum

Reputation: 2061

Why view functions require a request parameter In Django?

Example from Django documentation:

def index(request):
    return HttpResponse('<h1>hellworld!</h1>')

def detail(request, question_id):
    return HttpResponse("Question: %s" % question_id)

Since the request argument is never used, why should I include it in each function signature?

Upvotes: 6

Views: 2036

Answers (3)

dethos
dethos

Reputation: 3454

The purpose of a web server is to reply to HTTP requests (In simple terms). Django being a web framework generates responses depending on the request that it receives.

The business logic of handling the requests is done by Django Views, it is their purpose. This is why Django supplies the request to the view function, so the code can access the request data and choose what actions it should take and which response it should send back (even though that specific view doesn't make use of it).

The decision of requiring the view to receive the request as an argument is an implementation decision made by Django developers, making it part of the interface the view has with the rest of the "system". Other frameworks might choose making it available globally and not suplying it to the views/controllers directly, but the merits of one or another approach is other discussion.

Upvotes: 6

James Brewer
James Brewer

Reputation: 1755

Many of the examples in Django's documentation (and any documentation, really) are necessarily contrived. They're simple because the complexity of a real example would take away from the point that's being made.

In real use cases, you'll frequently want access to the request object. You may want to know which User is attached to the request (request.user) or whether the request is a GET or a POST (request.method).

You can also inspect the headers (request.headers), decode the JSON object sent with a POST request (json.loads(request.body)), etc.

Upvotes: 2

warvariuc
warvariuc

Reputation: 59674

Those are just examples. In real world a programmer would want to find request GET arguments, decode JSON POST body, inspect headers, get user or session data, etc.

Upvotes: 0

Related Questions