I would like to create a notification system I created the badge that signals me the notification on its page to see the various notifications and through ajax with the GET method I update the number of notifications. Not being attached to a single user, the count remains the number of notifications and I would like that user who clicks the 'read' button the notification is no longer seen and the conuter decreases. But how do I do it for the single user, I can do it but it would work for each user and not for the single one and that's it.
model
class Notification(models.Model):
date = models.DateField(auto_now_add = True)
title = models.CharField(max_length = 255)
text = models.TextField()
active = models.BooleanField(default = False)
View notification + view ajax notification
def notifiche(request):
if request.is_ajax() and request.method == "POST":
notifica = request.POST['id_notifica']
oggetto = get_object_or_404(Notification, id = notifica)
if oggetto.active == True:
oggetto.active = False
messaggio = "Notifica disattivata"
else:
oggetto.active = True
messaggio = "Notifica attiva sul sito"
oggetto.save()
return JsonResponse({'oggetto': oggetto.active, 'messaggio': messaggio}, status=200)
else:
notifiche = Notification.objects.all()
context = {'notifiche':notifiche, 'popup':popup}
return render(request, 'notifiche.html', context)
def popup(request):
popup = Notification.objects.filter(active = True).count()
return JsonResponse({'popup': popup}, status=200)
Snippets/nav.html
<nav class="navbar navbar-expand-lg bg-dark">
<div class="container">
<div class="collapse navbar-collapse justify-content-end">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link text-light" aria-current="page" href="{% url 'notifiche' %}">
Notifiche <span class="badge bg-danger">0</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
Ajax code in base.html
<script>
$.ajax({
url: "/ajax/notifiche/",
type: "GET",
dataType: 'json',
success: function(response){
$("nav span.badge").text(response.popup);
}
});
</script>