2016-08-30 34 views
1

我想向我的所有模板顯示我的通知。在我的設置,我有:使用context_processors將字典傳遞到所有模板

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

請出示您的看法 – Alasdair

回答

2

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 } 

然後在你的tempalate,您可以訪問{{ notifications.default }}

+0

感謝名單,你所建議正是我在第一時間做了(加的RequestContext像我當前的代碼之前)和我再次沒有結果,所以我懷疑可能是別的東西......我在我的settings.py中輸入了一個錯誤的地址,我沒有錯誤...所以我一起從settings.py中刪除了'TEMPLATES'選項仍然應用程序正在工作,沒有錯誤!我是否需要激活它或什麼? (我已經爲我的問題添加了版本) – hretic

+0

您的'TEMPLATES'設置看起來不錯。我沒問你問題,所以問題可能在那裏。 – Alasdair

+0

即使我從設置中刪除'TEMPLATES'或在其中輸入錯誤的地址也不會很奇怪嗎?我更新了我的代碼 – hretic