python - django 在模板中显示上下文数据而不通过 url 调用 View

标签 python django templates view

我写了一个 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/

相关文章:

java - 在多个输入文件上运行终端程序

python - 如何在 django 的日历应用程序中找到 "week"?

c++ - 检查成员函数是否存在且未被 SFINAE 继承

c++ - 模板使用代码错误

python - 让 pandas.read_csv() 忽略 csv 文件开头的垃圾?

python - 如何检查列表 'a' 中的元素是否满足列表 'b' 中的条件?

python - 如何划分轮廓?

python - 将 Django 模型转换为普通对象

python - Django,我在manage.py 检查或sync.db 时收到 "ERROR: Module: models could not be imported"

c++ - 模板模板参数