Adding a user to a group in django

前端 未结 3 1859
既然无缘
既然无缘 2020-11-28 02:55

How would I add a user to a group in django by the group\'s name?

I can do this:

user.groups.add(1) # add by id

How would I do some

3条回答
  •  醉话见心
    2020-11-28 03:19

    coredumperror is right but I have found one thing I need to share that one

    from django.contrib.auth.models import Group
    
    # get_or_create return error due to 
    new_group = Group.objects.get_or_create(name = 'groupName')
    print(type(new_group))       # return tuple
    
    new_group = Group.objects.get_or_create(name = 'groupName')
    user.groups.add(new_group)   # new_group as tuple and it return error
    
    # get() didn't return error due to 
    new_group = Group.objects.get(name = 'groupName')
    print(type(new_group))       # return 
    
    user = User.objects.get(username = 'username')
    user.groups.add(new_group)   # new_group as object and user is added
    

提交回复
热议问题