To access information from an HttpRequest object in a template, you need to pass the template a RequestContext object. The django.template.RequestContext is a special template context object that includes the information from the HttpRequest.
The RequestContext requires an HttpRequest object in its constructor when you create an instance. You can also specify an optional dictionary and a list of additional processors that add items to the context.
The following line of code creates a RequestContext object:
c = Reqest.context(request, {'aKey': 'aValue'})
RequestContext then automatically populates the context with some of the information from the request.
By the Way
What information is automatically populated in the RequestContext depends on which context processors are specified by the TEMPLATE_CONTEXTPROCESSORS setting in the settings.py file.
You can also specify your own processors when creating the RequestContext object. For example, the following code snippet defines a processor that gathers the remote hostname in the request and adds it to an instance of a RequestContext:
def get_host(request): return {'remote_host': request.META['REMOTE_HOST']} . . . def show_rhost_view(request) reqContext = RequestContext(request, {}, [get_host])
After you have created the RequestContext object, you can pass it as a context_instance argument to the render_to_response() function. The HttpRequest data in the RequestContext will be available in the template. The following code snippet shows how to add the RequestContext object to a render_to_response() function call:
return render_to_response('template.html', data_dictionary, context_instance= reqContext)
The following code snippet shows how to access the User object in the HttpRequest from a template file that was rendered using the RequestContext:
Hello {{ user.username }}
Did you Know?
If the user is not logged in, the user object in the RequestContext is an AnonymousUser object (which is described in Hour 14, "Managing Site Users").