Home > Enterprise >  allow users in a specific group to change posts UserPassesTestMixin
allow users in a specific group to change posts UserPassesTestMixin

Time:04-14

I have a user and a group called Manager. How do I allow a user in the Manager group to change a post that's not theirs?

Here's my code so far

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

And my models

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})

I get the error UserAccessMixin.test_func() missing 1 required positional argument: 'user'

Where do I go from here?

CodePudding user response:

You obtain the user with self.request.user, so:

from django.contrib.auth.mixins import LoginRequiredMixin

class UserAccessMixin(LoginRequiredMixin, UserPassesTestMixin):
    
    #       no user            
  • Related