目前我正在显示新通知标题的通知,他们有is_read = False,我想更新is_read = True并删除通知计数,这就是我在做什么
context_processor
def notification(request):
"""Provide the count of unread notifications for an authenticated user."""
if request.user.is_authenticated():
notifications = Notification.objects.filter(user=request.user, is_read=False).\
order_by('-created')[:5]
return {'notification_count': len(notifications),
'notifications': notifications}
else:
return {}
html模板和ajax调用
{% if notification_count >= 1 %}
<a id="notification_menu" data-toggle="dropdown" class="dropdown-toggle" href="#">
<i class="ace-icon fa fa-bell icon-animated-bell"></i>
<span class="badge badge-important">{{ payzaat_notification_count }}</span>
</a>
{% endif %}
<script type="text/javascript">
(function($){
$('#notification_menu').on("click",function(){
console.log('clicked');
$.ajax({
type: "GET",
url: "{% url 'parent:update_notification' %}",
dataType: 'json',
success: function(response){
return true;
},error:function(response){
return false;
}
});
});
})(jQuery);
</script>
更新视图
类UpdateNotification(FormView):
@method_decorator(parent_required)
def dispatch(self, request, *args, **kwargs):
return super(UpdateNotification, self).dispatch(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
for record in Notification.objects.filter(user=self.request.user, is_read=False):
record.is_read = True
record.save()
return HttpResponse("OKAY")
我的模型已更新,但模板仍显示计数,直到我刷新页面
答案 0 :(得分:0)
您必须清除ajax成功的通知计数:
success: function(response) {
$("#notification_menu span").text("");
}
答案 1 :(得分:0)
感谢nima
因为上下文处理器在页面渲染上运行所以 我这样做了
success: function(response) {
$(this + ".badge .badge-important").html("");
}