How to assign permissions to custom roles in custom User Model in Django?

I have defined a custom User Model that has 2 new roles beside superuser, staff and active, viz. candidate and voter. I want to assign permissions to these roles so that when I create the user with one of these ‘True’, I get the role-specific permissions assigned to the user automatically.

My User model is below

class User(AbstractBaseUser, PermissionsMixin):    
    username = models.CharField(max_length=254, null=True, blank=True)
    email = models.EmailField(max_length=254, unique=True)
    first_name = models.CharField(max_length=254, null=True, blank=True)
    last_name = models.CharField(max_length=254, null=True, blank=True)
    pbc_id = models.CharField(max_length=254, null=True, blank=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_candidate = models.BooleanField(default=False)
    is_voter = models.BooleanField(default=False)
    votes = models.IntegerField(default=0)
    last_login = models.DateTimeField(null=True, blank=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    
    USERNAME_FIELD = 'email'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()

    def get_absolute_url(self):
        return "/users/%i/" % (self.pk)

My UserManager class is below:

class UserManager(BaseUserManager):
    def _create_user(self, email, password, is_staff, is_superuser, is_candidate, is_voter, **extra_fields):
        if not email:
            raise ValueError('Users must have an email address')

        now = timezone.now()
        email = self.normalize_email(email)

        user = self.model(
            username=email,
            email=email,
            is_staff=is_staff, 
            is_active=True,
            is_superuser=is_superuser, 
            is_candidate=is_candidate,
            is_voter=is_voter,
            last_login=now,
            date_joined=now, 
            **extra_fields
        )
        user.set_password(password)
        user.save(using=self._db)
        user.pbc_id = "PBC-" + str(user.pk)
        user.save(using=self._db)
        return user

    def create_user(self, email, password, **extra_fields):
        user = self._create_user(email, password, False, False, False, False, **extra_fields)
        user.pbc_id = "PBC-" + str(user.pk)
        user.save(using=self._db)
        
        return user


    def create_superuser(self, email, password, **extra_fields):
        user=self._create_user(email, password, True, True, False, False, **extra_fields)
        return user

In admins.py, I have UserAdmin class a below:

class UserAdmin(BaseUserAdmin):
    fieldsets = (
        (None, {'fields': ('username', 'email', 'password', 'first_name', 'last_name', 'last_login')}),
        ('Permissions', {'fields': (
            'is_active', 
            'is_staff', 
            'is_superuser',
            'is_candidate',
            'is_voter',
            'groups', 
            'user_permissions',
        )}),
    )
    add_fieldsets = (
        (
            None,
            {
                'classes': ('wide',),
                'fields': ('email', 'password1', 'password2')
            }
        ),
    )

    list_display = ('username', 'email', 'first_name', 'last_name', 'pbc_id', 'is_staff', 'is_candidate', 'is_voter', 'last_login')
    list_filter = ('is_staff', 'is_candidate', 'is_voter', 'is_superuser', 'is_active', 'groups')
    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ('groups', 'user_permissions',)

If you’re looking to do this in the Admin, you can override the save_model method to add this functionality.

1 Like