开发者

Why is this Django template context processor not applied for all requests?

开发者 https://www.devze.com 2023-03-19 05:23 出处:网络
I\'ve run in to the following Django template context processor problem. The context processor is defined in myapp/context_processors.py:

I've run in to the following Django template context processor problem.

The context processor is defined in myapp/context_processors.py:

def my_context_processor(request):
    return {
        'foo': 123,
    }

It is wired up in setting开发者_Go百科s.py along with the standard Django context processors:

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'myproject.myapp.context_processors.my_context_processor',
)

The problem I'm encountering is that my_context_processor is not applied for all requests.

It is not applied for the following code:

def index(request):
    return render_to_response("index.html", locals())

However, it is applied for the following code:

def index(request):
    return render_to_response("index.html", locals(), context_instance=RequestContext(request))

I was under the impression that context processors are applied for ALL requests, not just when context_instance is provided.

How do I make my context processors being applied for ALL requests?


You have answered your own question. It's applied to the responses that use RequestContext. It's not applied to the ones that don't.

The way to get it to be applied to all responses is to make sure you always use RequestContext. Or, in Django 1.3+, you can use the new render shortcut instead of render_to_response, which creates a RequestContext for you.


Django introduced a new render shortcut in Django 1.3 which automatically includes the RequestContext

from django.shortcuts import render

def my_view(request):
    # View code here...
    context = {
        'some_extra_var_for_template': 'value'
    }
    return render(request, 'myapp/index.html', context)

You can read about it in the Django docs.


Context processor variables are only available when sending a RequestContext object (initialized with the current request) to the template as the context_instance.

0

精彩评论

暂无评论...
验证码 换一张
取 消