我想向我的所有模板显示我的通知。在我的设置中,我有:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'helpers.views.notifications' ,
],
},
},
]
helpers/views.py
def notifications():
notifications = {'A':'aaa' , 'B':'bbb' }
return {'notifications': notifications }
我的模板中没有任何内容 - 我做错了什么? 在模板中:
{{notifications.A}}
最佳答案
您的TEMPLATES
设置看起来没问题。在上下文处理器中,您不需要使用 RequestContext
。只需返回一本字典即可。如果您使用的是 Django 1.9 或更早版本,则必须调用方法request.user.is_authenticated()
,否则request.user.is_authenticated
将始终评估结果为 True。
def notifications(request):
if request.user.is_authenticated(): # Use request.user.is_authenticated for Django >= 1.10
notifications = {'default: 'logged in', ... }
else:
notifications = {'default':'not logged in', ...}
return {'notifications': notifications }
然后在您的模板中,您可以访问 {{ notification.default }}
关于python - 使用 context_processors 将字典传递给所有模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39230053/