extensions-website/notifications/views.py

64 lines
2.2 KiB
Python

"""Notifications pages."""
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseForbidden
from django.shortcuts import redirect
from django.utils import timezone
from django.views.generic import ListView
from django.views.generic.detail import SingleObjectMixin
from django.views.generic.edit import FormView
from django.views import View
from notifications.models import Notification
class NotificationsView(LoginRequiredMixin, ListView):
model = Notification
paginate_by = 20
def get_queryset(self):
filters = {'recipient': self.request.user}
if q := self.request.GET.get('q'):
if q == 'read':
filters['read_at__isnull'] = False
if q == 'unread':
filters['read_at__isnull'] = True
return (
Notification.objects.filter(**filters)
.select_related('action')
.prefetch_related('action__action_object', 'action__actor', 'action__target')
.order_by('-id')
)
def get_context_data(self):
ctx = super().get_context_data()
ctx['all_count'] = Notification.objects.filter(recipient=self.request.user).count()
return ctx
class MarkReadAllView(LoginRequiredMixin, FormView):
model = Notification
raise_exception = True
def post(self, request, *args, **kwargs):
"""Mark all previously unread notifications as read."""
unread = self.model.objects.filter(recipient=request.user, read_at__isnull=True)
now = timezone.now()
for notification in unread:
notification.read_at = now
Notification.objects.bulk_update(unread, ['read_at'])
return redirect('notifications:notifications')
class MarkReadView(LoginRequiredMixin, SingleObjectMixin, View):
model = Notification
raise_exception = True
def post(self, request, *args, **kwargs):
notification = self.get_object()
if notification.recipient != request.user:
return HttpResponseForbidden()
notification.read_at = timezone.now()
notification.save(update_fields=['read_at'])
return redirect('notifications:notifications')