我写了一个 View :
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(r'^notifications/', ShowNotifications.as_view(), name='notifin') 这样的 url 调用 View 时,
它显示了通知,但我希望它显示在弹出窗口。
我怎样才能使这成为可能......?? 需要帮助..
最佳答案
听起来您想将某些变量添加到每个 View 的上下文中,而不仅仅是这个 View 。
一种方法是使用 context processor :
# 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',
)
关于python - django 在模板中显示上下文数据而不通过 url 调用 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26966824/