python - 使用 context_processors 将字典传递给所有模板

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

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

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/

相关文章:

django - 对于模型,null=True 是否意味着 default=None?

python - 正则表达式有两个可选组,但不仅仅是第一组

python - 按值的绝对值对 Python 字典进行排序

python - SSH 无法在脚本内工作并给出错误 'ssh' 未被识别为内部或外部命令、可操作程序或批处理文件

python - Spark DataFrame TimestampType - 如何从字段中获取年、月、日值?

python - 在 Django 中将 Django-Hstore 用于 PostgreSQL HSTORE 时出错

python - 将最长的字段放入数据框列

python - Django:通过 pk 将模型添加到 ManyToMany,无需获取

python - 如何在单个变量python中使用多个pandas函数

python - 启用 SSL 时 Django 模块(嵌套管理和嵌套内联)的 ImportError