Search code examples
djangodjango-usersdjango-permissions

Django - How can I add a user to an auth_group?


I have and django application that I am trying to apply user group permissions. Here is how my members model is setup.

Class Member(AbstractUser)
    Class Meta:
        permissions = ((Perm1_codename, Perm1_desc),...)

pass
address = models.CharField(max_length=30)

When I migrate this, the permissions are saved in the auth_group_permissions table instead of the members_app_member_user_permissions table. I don't see a way to associate a user to the auth_group table because there is no user column in these tables.

I setup my roles in auth_group and defined the permission of each role in auth_group_permissions, how can I associate a user to these groups?

Alternatively, how can I add these user permissions to my members_app_member_user_permissions?


Solution

  • Django handles all the associations in the Auth App, so you don't have to worry about the tables much.. just know that Group<->User relations are Many-2-Many, and the relation is in a completely separate table.

    Here's the docs: https://docs.djangoproject.com/en/4.1/topics/auth/default/#permissions-and-authorization

    But also, here's the basics of Groups to get you started:

    Add a Single User to a Single Group

    from django.contrib.auth.models import Group, User
    
    user_obj = User.objects.get(username='nealiumj')
    group_obj = Group.objects.get(name='The Cool Kids')
    
    # From Group object
    group_obj.user_set.add(user_obj)
    
    # From User Object
    user_obj.groups.add(group_obj)
    

    Has/In Group

    from django.contrib.auth.models import User, Group
    
    user_obj = User.objects.get(username='nealiumj')
    has_group = user_obj.groups.filter(name='Lame').exists()
    
    print(has_group)  # False!
    
    ##
    
    group_obj = Group.objects.get(name='Lame')
    in_group = group_obj.user_set.filter(name='nealiumj').exists()
    
    print(in_group)  # Also False! ;)
    
    

    You can also add multiple users to a single group or add multiple groups to a single user using the *

    * adding. Multiple

    from django.contrib.auth.models import Group, User
    
    user_obj_list = User.objects.get(username__in=['nealiumj','also_me'])
    group_obj = Group.objects.get(name='The Cool Kids')
    
    # Multiple users to a single group
    group_obj.user_set.add(*user_obj_list)
    
    ###
    
    user_obj = User.objects.get(username='nealiumj')
    group_obj_list = Group.objects.get(name__in=['The Cool Kids', 'Super Attractive'])
    
    # Multiple groups to a single user
    user_obj.groups.add(*group_obj_list)
    

    I persume because your Member model is inheriting the User one, that all of these methods will be avaliable from the Member Objects as well