Skip to content

django


HttpRequest and HttpResponse

Django uses request and response objects to pass state through the system. These are part of the http request and response cycle. A client makes an http request, the server creates an http response.

When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object.

HttpRequest

The most important attributes are the GET and POST attributes. These are dictionaries containing all the information in the request. See QueryDict for more info.

Attribute Description
HttpRequest.scheme https or http
HttpRequest.path the url that was requested
HttpRequest.METHOD POST or GET
HttpRequest.FILES A dict containing all files in a POST request
HttpRequest.META length, type, hostname, sourceIP, destinationIP etc.
HttpRequest.user You can check if the user is authenticated or not

QueryDict

These objects are immutable.

request_data = HttpRequest.POST

name = request_data.get('name')
age = request_data.get('age')

HttpResponse

In contrast to HttpRequest objects, which are created automatically by Django, HttpResponse objects are your responsibility. Each view you write is responsible for instantiating, populating, and returning an HttpResponse.

These are normally generated by rendering a template with a context.

See also