Home > Back-end >  Django auth groups not finding groups and does not give permission to users, regardless of the group
Django auth groups not finding groups and does not give permission to users, regardless of the group

Time:04-03

I'm making a simple real estate app where the users must be separated into two different groups. A regular user and a broker. I'm using the Django admin backend for creating user groups. I'm also using a post_save signal to assign all the new users to the regular users' group. At first glance, it works well and in Django admin, it shows me that the user is in the corresponding group. But when I try to print self.request.user.groups the value is None. Also when I try to check if users have permission to do something, regardless of the permissions I gave the view I check always gives me 403 Forbidden regardless of whether the user has permission or not. I use class-based views and PermissionRequiredMixin respectively. Here is my user model:

class DjangoEstatesUser(auth_models.AbstractBaseUser, auth_models.PermissionsMixin):
USERNAME_MAX_LENGTH = 30

username = models.CharField(
    max_length=USERNAME_MAX_LENGTH,
    unique=True,
)

date_joined = models.DateTimeField(
    auto_now_add=True,
)

is_staff = models.BooleanField(
    default=False,
)

USERNAME_FIELD = 'username'

objects = DjangoEstatesUserManager()

Also the signal for assigning the new users to a group:

 @receiver(post_save, sender=DjangoEstatesUser)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        instance.groups.add(Group.objects.get(name='Users'))

and this is one view that I'm trying to restrict for different users:

class AddEstateView(auth_mixins.LoginRequiredMixin, auth_mixins.PermissionRequiredMixin, views.CreateView):
permission_required = 'auth_permission.add_estate'
template_name = 'main/estates/add_estate.html'
form_class = AddEstateForm

def get_form_kwargs(self):
    kwargs = super().get_form_kwargs()
    kwargs['user'] = self.request.user
    return kwargs

def get_success_url(self):
    return reverse_lazy('profile details', kwargs={'pk': self.object.user_id})

And these are the groups with the permissions. brokers_group and users_group.

And these are my db_tables and auth_permission_table.

I can't figure out where I'm wrong or what I'm not doing right, any help will be appreciated! Thank you in advance!

CodePudding user response:

self.request.user.groups prints always None: that is a RelatedManager [Django-doc], not a QuerySet. Managers will print the model name with None, so for a Model named ModelName in app_name, it prints:

app_name.ModelName.None

You print the items with self.request.user.groups.all():

print(self.request.user.groups.all())
  • Related