Skip to content

Commit

Permalink
Add Notification middleware to automatically mark notifications as read
Browse files Browse the repository at this point in the history
  • Loading branch information
anorthall committed Oct 30, 2023
1 parent c7978f2 commit 8fa5024
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
23 changes: 22 additions & 1 deletion app/users/middleware.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from zoneinfo import ZoneInfoNotFoundError

from django.utils import timezone
from users.models import CavingUser
from users.models import CavingUser, Notification


class DistanceUnitsMiddleware:
Expand Down Expand Up @@ -42,3 +42,24 @@ def __call__(self, request):
request.user.save(update_fields=["last_seen"])

return self.get_response(request)


class NotificationsMiddleware:
"""Mark a notification as read if a user goes on the page it links to."""

def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
if not request.user.is_authenticated:
return self.get_response(request)

unread_notifications = Notification.objects.filter(
user=request.user, read=False
)
for notification in unread_notifications:
if notification.get_url() == request.path:
notification.read = True
notification.save(update_fields=["read"])

return self.get_response(request)
1 change: 1 addition & 0 deletions config/django/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ def env(name, default=None, force_type: Any = str):
"users.middleware.TimezoneMiddleware",
"users.middleware.LastSeenMiddleware",
"users.middleware.DistanceUnitsMiddleware",
"users.middleware.NotificationsMiddleware",
]


Expand Down

0 comments on commit 8fa5024

Please sign in to comment.