【问题标题】:Django middleware process_template_response setupDjango 中间件 process_template_response 设置
【发布时间】:2015-06-25 20:24:48
【问题描述】:

我想创建一个函数来检查用户是否有任何通知。如果是,则该数字应显示在导航栏中。

有人可以帮我重构一下吗?

谢谢!

middleware.py:

def process_template_response(self, request, response):
    if request.user.is_authenticated():
        try:
            notifications = Notification.objects.all_for_user(request.user).unread()
            count = notifications.count()
            context = {
                "count": count
            }
            response = TemplateResponse(request, 'navbar.html', context)
            return response
        except:
            pass
    else:
        pass

navbar.html:

<li >
    <a href="{% url 'notifications_all' %}">
        {% if count > 0 %}Notifications ({{ count }}){% else %}Notifications{% endif %}
    </a>
</li>

【问题讨论】:

  • 为什么要在中间件中这样做?这是模板标签的工作。
  • @DanielRoseman 你能解释一下怎么做吗?

标签: python django django-templates django-middleware


【解决方案1】:

我以前做过类似的工作,我认为你应该使用context_data响应的属性:

class NotificationMiddleware(object):
    def process_template_response(self, request, response):
        if request.user.is_authenticated():
            try:
                notifications = Notification.objects.all_for_user(request.user).unread()
                count = notifications.count()
                response.context_data['count'] = count  # I recomend you to use other name instead of 'count'
                return response
            except Exception, e:
                print e  # Fix possible errors
                return response
        else:
            return response

然后你需要在settings 文件中的MIDDLEWARE_CLASSES 元组中注册这个类:

# settings.py
MIDDLEWARE_CLASSES = (
    # Django middlewares
    ....
    'yourapp.middleware.NotificationMiddleware',
)

上面的示例假设您的应用程序中有一个名为“yourapp”的middleware 文件夹。

最后你应该可以在模板中使用{{ count }}了。

【讨论】:

  • 谢谢!我将如何显示这是用于哪个模板?
  • 这将处理所有请求,因此您可以在每个模板中使用{{ count }}
  • 不幸的是,它对我不起作用。似乎没有任何事情发生
  • 您在设置文件中的MIDDLEWARE_CLASSES 中注册了吗?
  • 我刚刚更新了答案。我弄错了,它是context_data 而不是context
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-22
  • 1970-01-01
  • 2017-05-15
  • 1970-01-01
  • 2013-08-21
相关资源
最近更新 更多