Django - Limit users who view the items

By : anhtran

My Models:

class PromoNotification(models.Model):
    title = models.CharField(_('Title'), max_length=200)
    content = models.TextField(_('Content'))
    users = models.ManyToManyField(User, blank=True, null=True)
    groups = models.ManyToManyField(Group, blank=True, null=True)

I want to publish there items to templates with some permissions. The template is only show the notifications for users who are in list (users or/and group). What should I do? Thank you for any help. Please show me some codes if you can.

By : anhtran


You might use a custom manager, which makes it easier to do this user filtering in multiple views.

class PromoNotificationManager(models.Manager):
    def get_for_user(self, user)
        """Retrieve the notifications that are visible to the specified user"""
        # untested, but should be close to what you need
        notifications = super(PromoNotificationManager, self).get_query_set()
        user_filter = Q(groups__in=user.groups.all())
        group_filter = Q(users__in=user.groups.all())
        return notifications.filter(user_filter | group_filter)

Hook up the manager to your PromoNotification model:

class PromoNotification(models.Model):
    objects = PromoNotificationManager()

Then in your view:

def some_view(self):
    user_notifications = PromoNotification.objects.get_for_user(request.user)

You can read more about custom managers in the docs:

This video can help you solving your question :)
By: admin