View method responses
The render()
method
to generate view method responses you've used up to this point is
actually a shortcut. You can see toward the top of listing 2-23,
the render()
method is part of the
django.shortcuts
package.
This means there are other
alternatives to the render()
method to generate a view
response, albeit the render()
method is the most
common technique. For starters, there are three similar variations
to generate view method responses with data backed by a template,
as illustrated in listing 2-24.
Listing 2-24 Django view method response alternatives
---------------------------------------------------------------------------- # Option 1) from django.shortcuts import render def detail(request,store_id=1,location=None): ... context = {} return render(request,'stores/detail.html', context) ---------------------------------------------------------------------------- # Option 2) from django.template.response import TemplateResponse def detail(request,store_id=1,location=None): ... context = {} return TemplateResponse(request, 'stores/detail.html', context) ---------------------------------------------------------------------------- # Option 3) from django.http import HttpResponse from django.template import loader def detail(request,store_id=1,location=None): ... context = {} t = loader.get_template('stores/detail.html') return HttpResponse(t.render(context))
The first option in listing 2-24
is the django.shortcuts.render()
method which shows
three arguments to generate a response: the (required)
request
reference, a (required) template route and an
(optional) dictionary -- also known as the context -- with data to
pass to the template.
There are actually three more (optional)
arguments for the render()
method which are not shown
in listing 2-24: content_type
which sets the HTTP
Content-Type
header for the response and which
defaults to text/html
; status
which sets the HTTP
Status
code for the response which defaults to
200
that represents an HTTP 200 OK value; and using
to specify the template
engine -- either jinja2
or django
-- to
generate the response. The next section on HTTP handling for the
render()
method describes how to use
content_type
& status
, while chapters
3 & 4 talk about Django templates and Jinja templates.
The remaining content for Django 4.0 is only available with a subscription.