Django 1.4:为什么我的上下文处理器不工作?

Mat*_*esi 5 django django-templates django-1.4

我最近将一个项目从Django 1.3升级到1.4,这似乎打破了我的上下文处理器.

myapp/myapp/processors.py:

def currentPath(request):
    return {'current_path': request.get_full_path()}
Run Code Online (Sandbox Code Playgroud)

myapp/myapp/settings.py:

from django.conf import global_settings

global_settings.TEMPLATE_CONTEXT_PROCESSORS += (
    'myapp.processors.currentPath',
    'django.core.context_processors.request',
)
Run Code Online (Sandbox Code Playgroud)

在任何模板中,{{ current_path }}预期 - 并且在升级之前,返回当前路径.现在,它根本没有得到处理.我完全被困在这里了.

int*_*lis 5

Django 1.8增加处理器TEMPLATE_CONTEXT_PROCESSORS将无法正常工作。

Deprecated since version 1.8:
Set the 'context_processors' option in the OPTIONS of a DjangoTemplates backend instead.
Run Code Online (Sandbox Code Playgroud)

你必须这样做:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            # insert your TEMPLATE_DIRS here
        ],
        'OPTIONS': {
            'context_processors': [
                # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
                # list if you haven't customized them:
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
            ],
            'loaders': [
                # insert your TEMPLATE_LOADERS here
            ]
        },
    },
]
Run Code Online (Sandbox Code Playgroud)


sup*_*cuo 4

只是为了好玩,您是否会考虑以通常的方式指定该设置:

- global_settings.TEMPLATE_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',                                       
+     'django.core.context_processors.static',                                      
+     'django.contrib.messages.context_processors.messages',
     'myapp.processors.currentPath',
     'django.core.context_processors.request',
 )
Run Code Online (Sandbox Code Playgroud)

global_settings这可以消除您对问题根源的引用(看起来很有用!) 。

其次,如果你跑步

manage.py shell
Run Code Online (Sandbox Code Playgroud)

from myapp.processors import currentPath
Run Code Online (Sandbox Code Playgroud)

工作?您的项目结构似乎有点奇怪(我没有在settings.py以前的同一目录中看到上下文处理器; mycontext.py与 a 位于同一目录中models.py,我理解它通常不应与 位于同一目录中settings.py)。

(根据OP的要求从评论转换为答案)