View method requests
So far you've worked with Django
view methods and their input -- a request
object and
parameters -- as well as their output, consisting of generating a
direct response or relying on a template to generate a response.
However, now it's time to take a deeper look at what's available in
view method requests and the various alternatives to generate view
method responses.
The request
reference you've placed unquestionably in view methods up to this
point, is an instance of the
django.http.request.HttpRequest
class[3]. This request
object
contains information set by entities present before a view method:
a user's web browser, the web server that runs the application or a
Django middleware class configured on the application.
The following list shows some of
the most common attributes and methods available in a
request
reference:
request.method
.- Contains the HTTP method used for the request (e.g.GET
,POST
).request.GET
orrequest.POST
.- Contains parameters added as part of a GET or POST request, respectively. Parameters are enclosed as adjango.http.request.QueryDict
[4] instance.request.POST.get('name',default=None)
.- Gets the value of thename
parameter in a POST request or getsNone
if the parameter is not present. Notedefault
can be overridden with a custom value.request.GET.getlist('drink',default=None)
.- Gets a list of values for thedrink
parameter in a GET request or gets an empty listNone
if the parameter is not present. Notedefault
can be overridden with a custom value.request.META
.- Contains HTTP headers added by browsers or a web server as part of the request. Parameters are enclosed in a standard Python dictionary where keys are the HTTP header names -- in uppercase and underscore (e.g.Content-Length
as keyCONTENT_LENGTH
).request.META['REMOTE_ADDR']
.- Gets a user's remote IP address.request.user
.- Contains information about a Django user (e.g. username, email) linked to the request. Noteuser
refers to the user in thedjango.contrib.auth
package and is set via Django middleware, described later in this chapter.
As you can attest from this brief
list, the request
reference contains a lot of
actionable information to fulfill business logic (e.g. you can
respond with certain content based on geolocation information from
a user's IP address). There are well over fifty
request
options available between
django.http.request.HttpRequest
&
django.http.request.QueryDict
attributes and methods,
all of which are explained in parts of the book where they're
pertinent -- however you can review the full extent of
request
options in the footnote link of the django.http.request.HttpRequest
class.
Once you're done extracting
information from a request
reference and doing related
business logic with it (e.g. querying a database, fetching data
from a third party REST service) you then need to set up data in a
view method to send it out as part of a response.
The remaining content for Django 4.0 is only available with a subscription.