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

时间:2016-08-30 14:19:13

标签: 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' ,
            ],
        },
    },
]

助手/ views.py

def notifications():
    notifications =  {'A':'aaa' , 'B':'bbb' }
    return {'notifications': notifications }

我的模板中什么都没有 - 我做错了什么? 在模板中:

{{notifications.A}}

1 个答案:

答案 0 :(得分:2)

您的SELECT `debtortrans`.`transno`, debtortrans.type, custallocns.datealloc, debtortrans.id FROM `ts_demo`.`custallocns` INNER JOIN `ts_demo`.`debtortrans` as a ON a.`id` = custallocns`.`transid_allocfrom` INNER JOIN `ts_demo`.`debtortrans` as b ON b.`id` = `custallocns`.`transid_allocto` WHERE debtortrans.trandate >= LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 1 MONTH AND debtortrans.trandate < LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY AND debtortrans.settled = '1' AND debtortrans.type BETWEEN '10' AND '11' 设置看起来不错。在上下文处理器中,您不需要使用TEMPLATES。只需返回一本字典。如果您使用的是Django 1.9或更早版本,则必须调用方法RequestContext,否则request.user.is_authenticated()将始终评估为True。

request.user.is_authenticated

然后在您的状态中,您可以访问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 }