Home > database >  How to add multiple permission to user in django?
How to add multiple permission to user in django?

Time:07-19

I want to add multiple permission for a user in single api request. I have a array of permission code name, how to pass it in the view? Is for loop is the only way? or any other ting will work?

u = User.objects.get(username="admin_user_1")
permission = Permission.objects.get(name="Can add user")
u.user_permissions.add(permission)

This code can be used for single permission

CodePudding user response:

You can get a queryset of your permissions by checking if a field is present in a list - the list you can get through request.POST. You can then use * notation to expand the list into the m2m add() function:

u = User.objects.get(username="admin_user_1")
permissions_list = request.POST.getlist('permissions') # this may be differ
permissions = Permission.objects.filter(name__in=permissions_list)
u.user_permissions.add(*permissions)
  • Related