diff --git a/notifications/__init__.py b/notifications/__init__.py index be26720d..48437531 100644 --- a/notifications/__init__.py +++ b/notifications/__init__.py @@ -9,7 +9,7 @@ MAX_NOTIFICATIONS = 50 def notify(user, title, message=None, level='info'): from .models import Notification if Notification.objects.filter(user=user).count() > MAX_NOTIFICATIONS: - for n in Notification.objects.filter(user=user)[MAX_NOTIFICATIONS:]: + for n in Notification.objects.filter(user=user)[MAX_NOTIFICATIONS-1:]: n.delete() notif = Notification() notif.user = user diff --git a/notifications/handlers.py b/notifications/handlers.py index 6330fc49..6404d522 100644 --- a/notifications/handlers.py +++ b/notifications/handlers.py @@ -6,17 +6,27 @@ logger = logging.getLogger(__name__) class NotificationHandler(logging.Handler): def emit(self, record): - from django.contrib.auth.models import User + from django.contrib.auth.models import User, Permission + from django.db.models import Q + from notifications import notify from notifications.models import Notification - for user in User.objects.all(): - if user.has_perm('auth.logging_notifications'): - notif = Notification() - notif.user = user - notif.title = "%s [%s:%s]" % (record.levelname, record.funcName, record.lineno) - notif.level = str([item[0] for item in Notification.LEVEL_CHOICES if item[1] == record.levelname][0]) - message = record.getMessage() - if record.exc_text: - message += "\n\n" - message = message + record.exc_text - notif.message = message - notif.save() + + try: + perm = Permission.objects.get(codename="logging_notifications") + + message = record.getMessage() + if record.exc_text: + message += "\n\n" + message = message + record.exc_text + + users = User.objects.filter(Q(groups__permissions=perm) | Q(user_permissions=perm) | Q(is_superuser=True)).distinct() + + for user in users: + notify( + user, + "%s [%s:%s]" % (record.levelname, record.funcName, record.lineno), + level = str([item[0] for item in Notification.LEVEL_CHOICES if item[1] == record.levelname][0]), + message = message + ) + except Permission.DoesNotExist: + pass