[英]Post JS variables to Django view and display as context variables in separate template
[英]django display context data in template without calling view through url
我寫了一個觀點:
class ShowNotifications(TemplateView):
context = {}
model = Notification
template_name = "notifications.html"
def get_context_data(self, **kwargs):
context = super(ShowNotifications,self).get_context_data(**kwargs)
context['unseen_notifications'] = Notification.objects.filter(body__user=self.request.user).filter(viewed=False)
context['seen_notifications'] = Notification.objects.filter(body__user=self.request.user).filter(viewed=True)
return context
我在我的模板中顯示了它的上下文。 我已經創建了一個通知彈出窗口,用戶可以在Facebook中查看通知,登錄后可以看到他們的通知。
我制作了“notifications.html”並將其包含在通知導航中。 當我點擊它不顯示任何東西。 但是,當我通過URL調用視圖時,如url(r'^notifications/', ShowNotifications.as_view(), name='notifin') ,
它會顯示通知,但我希望它會彈出顯示。
我怎樣才能做到這一點...... 需要幫忙..
我認為通過“include”模板標簽包含模板視圖是不可能的。 在當前上下文中包含加載模板https://docs.djangoproject.com/en/dev/ref/templates/builtins/#include 。
在我看來,您應該使用自定義模板標記。 https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
聽起來你想要將某些變量添加到每個視圖的上下文中,而不僅僅是這個。
一種方法是使用上下文處理器 :
# myapp/context_processors.py
def notifications(request):
"Context processor for adding notifications to the context."
return {
'unseen_notifications': Notification.objects.filter(
body__user=request.user).filter(viewed=False),
'seen_notifications': Notification.objects.filter(
body__user=request.user).filter(viewed=True),
}
您還需要將上下文處理器添加到TEMPLATE_CONTEXT_PROCESSORS:
# settings.py
...
TEMPLATE_CONTEXT_PROCESSORS = (
...
'myapp.context_processors.notifications',
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.