允许特定组中的用户更改帖子 UserPassesTestMixin
allow users in a specific group to change posts UserPassesTestMixin
我有一个用户和一个名为 Manager 的组。如何允许 Manager 组中的用户更改不属于他们的 post?
到目前为止,这是我的代码
class UserAccessMixin(UserPassesTestMixin):
def test_func(self, user):
issue = self.get_object()
mod = user.get_object()
if self.request.user == issue.author:
return True
elif user.object.user == mod.groups.filter(name='Manager').exists():
return True
return False
还有我的模特
class Issue(models.Model):
MARK_AS = ((True, 'Open'), (False, 'Closed'))
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
assignee = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True, blank=True)
mark_as = models.BooleanField(choices=MARK_AS, default=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('issue-detail', kwargs={'pk': self.pk})
我收到错误 UserAccessMixin.test_func() missing 1 required positional argument: 'user'
我从这里去哪里?
你用self.request.user
获取用户,所以:
from django.contrib.auth.mixins import LoginRequiredMixin
class UserAccessMixin(LoginRequiredMixin, UserPassesTestMixin):
# <em>no</em> user 🖟
def test_func(self):
user = self.request.user
return user.groups.filter(name='Manager').exists() or self.get_object().author == user
我有一个用户和一个名为 Manager 的组。如何允许 Manager 组中的用户更改不属于他们的 post?
到目前为止,这是我的代码
class UserAccessMixin(UserPassesTestMixin):
def test_func(self, user):
issue = self.get_object()
mod = user.get_object()
if self.request.user == issue.author:
return True
elif user.object.user == mod.groups.filter(name='Manager').exists():
return True
return False
还有我的模特
class Issue(models.Model):
MARK_AS = ((True, 'Open'), (False, 'Closed'))
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
assignee = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True, blank=True)
mark_as = models.BooleanField(choices=MARK_AS, default=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('issue-detail', kwargs={'pk': self.pk})
我收到错误 UserAccessMixin.test_func() missing 1 required positional argument: 'user'
我从这里去哪里?
你用self.request.user
获取用户,所以:
from django.contrib.auth.mixins import LoginRequiredMixin
class UserAccessMixin(LoginRequiredMixin, UserPassesTestMixin):
# <em>no</em> user 🖟
def test_func(self):
user = self.request.user
return user.groups.filter(name='Manager').exists() or self.get_object().author == user