Describes how to use context in the Django framework to parse the template, djangocontext

Source: Internet
Author: User

Describes how to use context in the Django framework to parse the template, djangocontext

You need a context to parse the template. Generally, this is an example of django. template. Context. However, you can use a special subclass Django. template. RequestContext in django, which is slightly different in use. By default, RequestContext adds some variables to the template context, such as the HttpRequest object or information about the currently logged-on user.

If you do not want to specify the same variables in a series template, you should use RequestContext. For example, consider the two views:

from django.template import loader, Contextdef view_1(request):  # ...  t = loader.get_template('template1.html')  c = Context({    'app': 'My app',    'user': request.user,    'ip_address': request.META['REMOTE_ADDR'],    'message': 'I am view 1.'  })  return t.render(c)def view_2(request):  # ...  t = loader.get_template('template2.html')  c = Context({    'app': 'My app',    'user': request.user,    'ip_address': request.META['REMOTE_ADDR'],    'message': 'I am the second view.'  })  return t.render(c)

(Note: In these examples, we intentionally did not use the render_to_response () shortcut. Instead, we chose to manually load the template, manually construct the context object, and then render the template. To clearly illustrate all the steps .)

Each view imports three Identical variables to the template: app, user, and ip_address. Will it be better if we remove the redundancy?

The RequestContext and context processors are created to solve this problem. The Context processor allows you to set some variables, which will be automatically set in each context, instead of being specified every time you call render_to_response. The key point is that when you render a template, you must use RequestContext instead of Context.

The most direct approach is to use the context processor to create some processors and pass them to RequestContext. The preceding example can be rewritten using context processors as follows:

from django.template import loader, RequestContextdef custom_proc(request):  "A context processor that provides 'app', 'user' and 'ip_address'."  return {    'app': 'My app',    'user': request.user,    'ip_address': request.META['REMOTE_ADDR']  }def view_1(request):  # ...  t = loader.get_template('template1.html')  c = RequestContext(request, {'message': 'I am view 1.'},      processors=[custom_proc])  return t.render(c)def view_2(request):  # ...  t = loader.get_template('template2.html')  c = RequestContext(request, {'message': 'I am the second view.'},      processors=[custom_proc])  return t.render(c)

Let's read through the Code:

First, we define a custom_proc function. This is a context processor that receives an HttpRequest object and returns a dictionary containing variables that can be used in the template context. It does so much.

We use RequestContext in these two view functions to replace Context. There are two differences in Building context objects. 1. The first parameter of RequestContext needs to pass an HttpRequest object, that is, the first parameter (request) passed to the view function ). 2. RequestContext has an optional parameter processors, which is a list or tuples containing the context processor function. Here, we passed the previously defined processor function curstom_proc.

The context structure of each view no longer contains app, user, ip_address, and other variables, because these are provided by the custom_proc function.

Each view still has great flexibility and can introduce any template variables we need. In this example, the message template variables are different in each view.

To explain how the context processor works at the underlying layer, we did not use render_to_response () in the above example (). However, we recommend that you use render_to_response () as the context processor. In this case, the context_instance parameter is used:

from django.shortcuts import render_to_responsefrom django.template import RequestContextdef custom_proc(request):  "A context processor that provides 'app', 'user' and 'ip_address'."  return {    'app': 'My app',    'user': request.user,    'ip_address': request.META['REMOTE_ADDR']  }def view_1(request):  # ...  return render_to_response('template1.html',    {'message': 'I am view 1.'},    context_instance=RequestContext(request, processors=[custom_proc]))def view_2(request):  # ...  return render_to_response('template2.html',    {'message': 'I am the second view.'},    context_instance=RequestContext(request, processors=[custom_proc]))

Here, we write the template rendering code of each view into a single line.

Although this is an improvement, consider the simplicity of this Code. What we have to admit is that it is too much on the other hand. We eliminate data redundancy (our template variables) at the cost of code redundancy (in processors calls ). Since you have to keep typing processors, using the context processor does not reduce too much input.

Django therefore provides support for the global context processor. TEMPLATE_CONTEXT_PROCESSORS specifies which context processors are always used by default. This saves the trouble of specifying processors every time you use RequestContext.

By default, TEMPLATE_CONTEXT_PROCESSORS is set as follows:

TEMPLATE_CONTEXT_PROCESSORS = (  'django.core.context_processors.auth',  'django.core.context_processors.debug',  'django.core.context_processors.i18n',  'django.core.context_processors.media',)

This setting item is a tuples of callable functions. Each function uses the same interface as the preceding custom_proc. They use the request object as the parameter, returns a dictionary that will be merged and passed to the context: receives a request object as a parameter, and returns a dictionary containing the items that will be merged into the context.

Each processor will be applied in order. That is to say, if you add a variable to the context in the first processor, and the second processor adds a variable with the same name, the second will overwrite the first variable.

Django provides several simple context processors, some of which are enabled by default.

Django. core. context_processors.auth

If TEMPLATE_CONTEXT_PROCESSORS includes this processor, each RequestContext will contain these variables:
  • User: A django. contrib. auth. models. User instance that describes the current login user (or an AnonymousUser instance if the client is not logged on ).
  • Messages: a message list (string) of the currently logged-on user ). In the background, for each request, this variable calls the request. user. get_and_delete_messages () method. This method collects user messages and deletes them from the database.
  • Perms: an instance of django. core. context_processors.PermWrapper that contains the permissions of the current logon user.

For more information about users, permissions, and messages, see Chapter 14th.
Django. core. context_processors.debug

This processor sends debugging information to the template layer. If TEMPLATE_CONTEXT_PROCESSORS contains this processor, each RequestContext will contain these variables:

  • Debug: the DEBUG value you set (True or False ). You can use this variable in the template to test whether it is in debug mode.
  • SQL _queries: contains something similar to ''{'SQL ':..., A list of 'time': ''dictionaries that record the time spent in each SQL query and query during this request. The list is arranged in the Request order.
  • System Message: WARNING/2 (<string>, line 315); backlink
  • Inline literal start-string without end-string.
  • Because the debugging information is sensitive, this context processor is valid only when both of the following conditions are met:
  • Set the DEBUG parameter to True.
  • The requested ip address should be included in INTERNAL_IPS settings.

Careful readers may notice that the value of the debug template variable cannot always be False, because if DEBUG is False, the debug template variable will not be included in RequestContext at the beginning.
Django. core. context_processors.i18n

If this processor is enabled, each RequestContext will contain the following variables:

  • Ages: the value of the ages option.
  • Required age_code: If request. Required age_code exists, it is equal to it; otherwise, it is equivalent to the setting of required age_code.

Django. core. context_processors.request

If this processor is enabled, each RequestContext will contain the variable request, which is the current HttpRequest object. Note that this processor is disabled by default, and you need to activate it.

If you find that your template needs to access the current HttpRequest, you need to use it:

{Request. REMOTE_ADDR }}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.