[Django]-Django – Trouble adding User to User Group with custom User Model

5👍

What’s your custom job user model?

Maybe you inherit AbstractUser or AbstractBaseUser.

But when you need to use groups, ou have to inherit PermissionsMixin

    from django.contrib.auth.models import PermissionMixin

you can check in django github code here

here’s part of the code

class PermissionsMixin(models.Model):
    """
    Add the fields and methods necessary to support the Group and Permission
    models using the ModelBackend.
    """
    is_superuser = models.BooleanField(
        _('superuser status'),
        default=False,
        help_text=_(
            'Designates that this user has all permissions without '
            'explicitly assigning them.'
        ),
    )
    groups = models.ManyToManyField(
        Group,
        verbose_name=_('groups'),
        blank=True,
        help_text=_(
            'The groups this user belongs to. A user will get all permissions '
            'granted to each of their groups.'
        ),
        related_name="user_set",
        related_query_name="user",
    )

Hope solving well!

Adding

This is my part of user model. You should inherit both BaseUser and PermissionsMixin. Then you can use groups from PermissionsMixin.

class JobUser(AbstractBaseUser, PermissionsMixin, TimeStampedModel):
    email = models.EmailField(
        verbose_name="Email",
        max_length=255,
        unique=True,
        db_index=True,
    )
    user_type = models.PositiveIntegerField(
        verbose_name="User type",
        # 0 - staff
        # 1 - employer
        # 2 - employee
        choices=CHOICES.USER_CHOICES,
        default=2,
    )
    ...

So your User model will be like…

class User(AbstractBaseUser, PermissionsMixin):
    first_name = models.CharField(max_length=255, blank=True, null=True)
    last_name = models.CharField(max_length=255, blank=True, null=True)
    email = models.EmailField(max_length=255, unique=True)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    # active = models.BooleanField(default=True) #can login
    staff = models.BooleanField(default=False) #staff not superuser
    admin = models.BooleanField(default=False) #superuser
    ...

Also don’t forget import PermissionMixin in top of your code.

Hope solving well!

Leave a comment