简体   繁体   English

Django:上下文处理器未在登录页面上运行?

[英]Django: Context processor not being run on login page?

I have created a context processor which aims to pass a certain variable to any template that gets loaded. 我创建了一个上下文处理器,旨在将某个变量传递给要加载的任何模板。

This is how I have defined my context processor: 这就是我定义上下文处理器的方式:

from django.conf import settings

def theme(request):
    return {'custom_theme': getattr(settings, "CUSTOM_THEME", "default")}

This is how I have included my context processor in the settings file: 这就是我将上下文处理器包含在设置文件中的方式:

TEMPLATES = [{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'APP_DIRS': True,
    'DIRS': [
        normpath(join(PROJECT_PATH, 'templates')),
    ],
    'OPTIONS': {
        'context_processors': {
            'django.template.context_processors.request',
            'django.template.context_processors.media',
            'django.contrib.auth.context_processors.auth',
            'myapp.context_processor.theme',
        },
        'debug': False,
    }
}]

However, for some reason, it is not always being executed, mainly in the login page. 但是,由于某些原因,它并不总是被执行,主要是在登录页面中。

This is the view that handles the login URL and return a 'TemplateResponse`: 这是处理登录URL并返回'TemplateResponse`的视图:

@never_cache
@sensitive_post_parameters('password')
@csrf_protect
def custom_login(request):

    redirect_field_name = 'next'
    redirect_to = request.POST.get(redirect_field_name,
                                   request.GET.get(redirect_field_name, ''))

    if request.method == "POST":
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():

            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())

            if getattr(settings, 'CHECK_PERMISSIONS_ON_CMDB', False):
                logger.info('Checking permissions on CMDB.')
                auth_cmdb_user_realms(form.get_user())

            return HttpResponseRedirect(redirect_to)
    else:
        form = AuthenticationForm(request)

    context = {
        'form': form,
        'version': get_project_version(),
        redirect_field_name: redirect_to,
    }

    if hasattr(settings, "CUSTOM_THEME"):
        login_template = 'custom_auth/themes/{}/login.html'.\
             format(settings.CUSTOM_THEME)
    else:
        login_template = 'custom_auth/themes/default/login.html'

    return TemplateResponse(request, login_template, context)

Since the context processor is not being run, the variable ustom_theme` is not being inserted in the context and I get the following error: 由于未运行上下文处理器,因此未在上下文中插入变量ustom_theme`,并且出现以下错误:

VariableDoesNotExist: Failed lookup for key [custom_theme] in u"[{'False': False, 'None': None, 'True': True, 'compressed': {'name': None}}]"

The strange thing is that sometimes the context processor is being executed. 奇怪的是,有时上下文处理器正在执行。

Does anybody have any idea why te context processor is not being run when trying to load the login page? 有人知道尝试加载登录页面时为什么不运行上下文处理器吗?

Context processors is not used if you doesn't call it. 如果您不调用上下文处理器,则不会使用它。

The long path: 长路:

return render_to_response("my_app/my_template.html", {'some_var': 'foo'},
                           context_instance=RequestContext(request))

The short path: 短路径:

from django.shortcuts import render

def some_view(request):
   ...Do something....
   return render(request, "MyTemplate.html",{})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM