我创建了一个上下文处理器,旨在将某个变量传递给任何加载的模板。
这就是我定义上下文处理器的方式:
from django.conf import settings
def theme(request):
return {'custom_theme': getattr(settings, "CUSTOM_THEME", "default")}
这就是我在设置文件中包含我的上下文处理器的方法:
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,
}
}]
但是,由于某种原因,它并不总是被执行,主要是在登录页面。
这是处理登录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)
由于没有运行上下文处理器,变量ustom_theme`没有插入上下文中,我收到以下错误:
VariableDoesNotExist: Failed lookup for key [custom_theme] in u"[{'False': False, 'None': None, 'True': True, 'compressed': {'name': None}}]"
奇怪的是,有时上下文处理器正在执行。
有没有人知道为什么在尝试加载登录页面时没有运行上下文处理器?
答案 0 :(得分:1)
如果您不调用它,则不使用上下文处理器。
漫长道路:
return render_to_response("my_app/my_template.html", {'some_var': 'foo'},
context_instance=RequestContext(request))
短路径:
from django.shortcuts import render
def some_view(request):
...Do something....
return render(request, "MyTemplate.html",{})