mrabot
mrabot

Reputation: 1

request.user.group returns auth.Group.None for Django custom user model

Created custom user model, initially without PermissionsMixin, then realized, that I will need it, and added. Makemigrations, migrate - done.

class UserProfile(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(
    verbose_name='email address',
    max_length=255,
    unique=True,
    )

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name']
    first_name = models.CharField(max_length=50, blank=True, null=True)
    middle_name = models.CharField(max_length=50, blank=True, null=True)
    last_name = models.CharField(max_length=50, blank=True, null=True)
[..]

Solution, works partially. I can add user to the group, db is updated, can see the relation, but user.groups returns None. What am I doing wrong? How to troubleshoot it?

    for group in Group.objects.filter():
        print(group, group.id)    
    request.user.groups.add(Group.objects.get(id=2))
    print(Group.objects.get(user=request.user))
    print(request.user.groups)

gives output:

individual_customers 1
business_customers 2
staff 3
business_customers
auth.Group.None

Upvotes: 0

Views: 345

Answers (1)

0sVoid
0sVoid

Reputation: 2663

Django permission Groups are many-to-many relations, so you need to call them like so:

request.user.groups.all()

It should return a queryset with all the group permissions that are related to the user

Upvotes: 1

Related Questions