djangopython-3.xdjango-guardian

How to use django-guardian in customized user model


I am using django-guardian to check the user's object permission. And in my special case, I have extended user model. In my models.py I have extended user model like this: enter image description here

class User(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False) 
    admin = models.BooleanField(default=False) 

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = [] # Email & Password are required by default.

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):              # __unicode__ on Python 2
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        return self.staff

    @property
    def is_admin(self):
        "Is the user a admin member?"
        return self.admin

    @property
    def is_active(self):
        "Is the user active?"
        return self.active

And in my object model, I have added a Meta class for permission: enter image description here

class task(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        permissions = (
            ('view_task', 'View task'),
        )

    def __str__(self):
        return self.name

After doing makemigrations and migrate, when I run below test in python manage.py shell, it always calls the has_perm function in my user model and returns the value of that function, which is True.

>>>from myapp.models import User, task
>>>setuser = User.objects.get(email = 'joe@gmail.com')
>>>task = exclusionDomain.objects.get(name = 'task1')
>>>setuser.has_perm('view_task', task)

How do I fix this problem? Or is there any useful tutorial of how to use guardian in a customized user model?


Solution

  • If anyone has the same problem. Here is the solution:

    Instead of using AbstractBaseUser, use AbstractUser. AbstractBaseUser is not compatible with django-guardian. And according to the guardian documentation, extended user model using AbstractUser should be okay. And it also worked for me.

    Here is the tutorial of how to extend user model by using AbstractUser: https://wsvincent.com/django-custom-user-model-tutorial/