如何在 Django 中检查用户是否是模型对象的成员?

How to check user is a member of model object or not in Django?

我在 model.py

中写了这个模型
class Group(models.Model):
   MEMBERS_NUMBER = [
      (2, 'Two people'),
      (5, '3 to 5'),
      (10, '5 to 10'),
   ]
   group_name = models.CharField(max_length=50)
   slug = models.SlugField(max_length=50, unique=True)
   members = models.IntegerField(choices=MEMBERS_NUMBER)
   people = models.ManyToManyField('Profile', through='Membership', blank = True)
   summary = models.TextField(
      'Summary and indeas',
      max_length=500,
      help_text='Say what you want to do with your study or jub partner.'
   )
   date_created = models.DateTimeField(default=timezone.now)

class Profile(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE)
  birth_date = models.DateField(blank=True, null=True)
  profile_picture = models.ImageField(default = 'default.jpeg', upload_to = 'profile_pics', null=True, blank = True)
  date_joined = models.DateTimeField(default=timezone.now, null=True, blank = True)

class Membership(models.Model):
  group = models.ForeignKey(Group, on_delete=models.CASCADE)
  members = models.ForeignKey(Profile, on_delete=models.CASCADE)

然后我为组模型的每个对象创建了基于 class 的通用视图,但我想限制对该组对象中的配置文件的访问,这是我的基于 class 的视图:

class GroupDetail(UserPassesTestMixin, generic.DetailView):
  model = models.Group
  context_object_name = 'group'
  template_name = 'projects/group_detail.html'

  def test_func(self):
    return self.request.user.profile.group_set.filter(group_name='My-Django-Group')

  def get_queryset(self):
    return models.Group.objects.all()

test_func(self) 检查用户是否是 'My-Django-Group' 的成员,然后向用户显示组详细信息,但我想获取我们在其中的对象名称,我测试了这个:

def test_func(self):  
return self.request.user.profile.group_set.filter(group_name=self.group.group_name)

但是没用

您可以使用以下方法过滤查询集:

from django.contrib.auth.mixins import LoginRequiredMixin

class GroupDetail(LoginRequiredMixin, generic.DetailView):
  model = models.Group
  context_object_name = 'group'
  template_name = 'projects/group_detail.html'

  def <b>get_queryset</b>(self):
    return super().get_queryset().filter(
        <strong>people__user=self.request.user</strong>
    )

如果用户不是该组的成员,他们将收到 HTTP 404 响应。


Note: You can limit views to a class-based view to authenticated users with the LoginRequiredMixin mixin [Django-doc].