如何在Django 1.10的新TEMPLATES设置中包含默认的TEMPLATE_CONTEXT_PROCESSORS

Ale*_*all 6 python django django-templates

我正在将项目升级到Django 1.10,它的代码如下:

from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP

TEMPLATE_CONTEXT_PROCESSORS = TCP + (
    'django.template.context_processors.debug',
    'django.template.context_processors.i18n',
    'django.template.context_processors.media',
    'django.template.context_processors.static',
    'django.contrib.auth.context_processors.auth',
    'django.contrib.messages.context_processors.messages',
    'django.template.context_processors.request',
)
Run Code Online (Sandbox Code Playgroud)

据我所知,这是使用以前版本的Django时的常见模式,以确保默认的上下文处理器.

在Django 1.10 TEMPLATE_CONTEXT_PROCESSORS中删除了有利于TEMPLATES设置,现在应该定义如下:

TEMPLATES = [
    {
        ...,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                ...
            ],
        },
    },
]
Run Code Online (Sandbox Code Playgroud)

如何TEMPLATES定义设置以正确匹配第一个代码示例的行为,即确保始终包含默认上下文处理器?我应该手动包含django.conf.global_settings之前的内容吗?Django 1.10是否在任何地方定义了默认值?是否有任何新的上下文处理器可能默认包含在内?

Olu*_*ule 0

如果在 python 3 上运行,请在默认上下文处理器之前解压 TCP。

from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP

# Python 3.6
TEMPLATES = [
    {
        ...,
        'OPTIONS': {
            'context_processors': [
                *TCP,
                'django.template.context_processors.debug',
                ...
            ],
        },
    },
]
Run Code Online (Sandbox Code Playgroud)

在较低版本上

对于单个模板配置:

TEMPLATE = {
        ...,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                ...
            ],
        },
    }

TEMPLATE['OPTIONS']['context_processors'] = (
    TCP + TEMPLATE['OPTIONS']['context_processors'])

TEMPLATES = [TEMPLATE, ]
Run Code Online (Sandbox Code Playgroud)

对于多个模板配置:

TEMPLATES = [...]

for template in TEMPLATES:
    template['OPTIONS']['context_processors'] = (
        TCP + template['OPTIONS']['context_processors'])
Run Code Online (Sandbox Code Playgroud)