Tuesday, July 3, 2007

RequestContext in Template

def some_view(request):
# ...
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))

Here’s what each of the default processors does:

django.core.context_processors.auth

If TEMPLATE_CONTEXT_PROCESSORS contains this processor, every RequestContext will contain these three variables:

  • user — An auth.User instance representing the currently logged-in user (or an AnonymousUser instance, if the client isn’t logged in). See the user authentication docs.

  • messages — A list of messages (as strings) for the currently logged-in user. Behind the scenes, this calls request.user.get_and_delete_messages() for every request. That method collects the user’s messages and deletes them from the database.

    Note that messages are set with user.message_set.create. See the message docs for more.

  • perms — An instance of django.core.context_processors.PermWrapper, representing the permissions that the currently logged-in user has. See the permissions docs.

django.core.context_processors.debug

If TEMPLATE_CONTEXT_PROCESSORS contains this processor, every RequestContext will contain these two variables — but only if your DEBUG setting is set to True and the request’s IP address (request.META['REMOTE_ADDR']) is in the INTERNAL_IPS setting:

  • debugTrue. You can use this in templates to test whether you’re in DEBUG mode.
  • sql_queries — A list of {'sql': ..., 'time': ...} dictionaries, representing every SQL query that has happened so far during the request and how long it took. The list is in order by query.

django.core.context_processors.i18n

If TEMPLATE_CONTEXT_PROCESSORS contains this processor, every RequestContext will contain these two variables:

See the internationalization docs for more.

django.core.context_processors.media

If TEMPLATE_CONTEXT_PROCESSORS contains this processor, every RequestContext will contain a variable MEDIA_URL, providing the value of the MEDIA_URL setting.

django.core.context_processors.request

If TEMPLATE_CONTEXT_PROCESSORS contains this processor, every RequestContext will contain a variable request, which is the current HttpRequest object. Note that this processor is not enabled by default; you’ll have to activate it.

Writing your own context processors

A context processor has a very simple interface: It’s just a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.

Custom context processors can live anywhere in your code base. All Django cares about is that your custom context processors are pointed-to by your TEMPLATE_CONTEXT_PROCESSORS setting.


No comments: