Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add multiple permission to user in django?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading