【问题标题】:passing a dictionary to all templates using context_processors使用 context_processors 将字典传递给所有模板
【发布时间】:2017-01-06 21:21:18
【问题描述】:

我想向我的所有模板显示我的通知。在我的设置中,我有:

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}}

【问题讨论】:

  • 请展示你的观点

标签: python django python-3.x django-1.9


【解决方案1】:

您的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 }

然后在你的模板中,你可以访问{{ notifications.default }}

【讨论】:

  • thanx ,您的建议正是我最初所做的(在像我当前的代码一样添加 RequestContext 之前),我又做了一次没有结果,所以我很怀疑可能是什么否则......我在我的settings.py中输入了错误的地址我没有错误......所以我从settings.py中删除了TEMPLATES选项,所有这些仍然应用程序没有错误地工作!我需要激活它还是什么? (我已经为我的问题添加了版本)
  • 您的TEMPLATES 设置看起来不错。你没有按照我的要求展示你的观点,所以问题可能就在那里。
  • 没有我说即使我从设置中删除TEMPLATES 或在其中输入错误的地址它也能正常工作,这不是很奇怪吗?我已经更新了我的代码
  • 我认为从您的设置中删除TEMPLATES 不会帮助您调试问题。如果您删除 TEMPLATES,那么我相信 Django 1.9 假定您使用的是旧版 TEMPLATE_ 设置。
  • @hretic 你是在 Django 的开发服务器还是 Apache/nginx 等上运行?如果是后者,您可能需要重新启动该过程才能使更改生效
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-19
  • 2015-10-23
  • 2021-07-27
  • 2016-11-25
  • 1970-01-01
  • 1970-01-01
  • 2014-12-17
相关资源
最近更新 更多