Django - 限制查看项目的用户

时间:2010-08-04 11:00:15

标签: python django django-models django-templates

我的模特:

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)

我想将项目发布到具有某些权限的模板。模板仅显示列表中用户(用户或/和组)的通知。我该怎么办?感谢您的任何帮助。如果可以,请告诉我一些代码。

1 个答案:

答案 0 :(得分:4)

您可以使用自定义管理器,这样可以更轻松地在多个视图中执行此用户过滤。

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)

将经理连接到您的PromoNotification模型:

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

然后在你看来:

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

您可以在文档中详细了解自定义管理器:http://www.djangoproject.com/documentation/models/custom_managers/