views:

40

answers:

1

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.

+1  A: 

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: http://www.djangoproject.com/documentation/models/custom_managers/

Chris Lawlor
Some misstakes but this is a good idea. Thanks!group_filter = Q(groups__in=user.groups.all())user_notifications = PromoNotification.objects.get_for_user(request.user)
Tran Tuan Anh
Thanks for posting the mistakes you found. I've updated the answer to include your fixes.
Chris Lawlor