Django Python : adding custom permissions to specific users

Vinay Guda picture Vinay Guda · Feb 27, 2018 · Viewed 7.1k times · Source

Models.py

class Meta:
    permissions = (
        ("can_add_data","can add a new data"),
        )

This is the custom permission I've created in Models.py and I've also created these users.

Users in Django Admin ie., http://localhost:8000/admin

How do I give permission to specific users so that I can use @permission_required('myapp.can_add_data') in views.py and also where do I write the snippet? (in which file)

I'm a beginner at this so if there are any mistakes please let me know.

Answer

JPG picture JPG · Feb 27, 2018

You can assign permission to user through either Django Admin or Django shell
through django-shell
open your django shell by python manage.py shell and run the following statements

In [1] from django.contrib.auth.models import Permission,User
In [2] permission = Permission.objects.get(name='can add a new data')
In [3] user = User.objects.get(id=user_id)
In [4] user.user_permissions.add(permission)


through django-admin
open your django-admin page and head to Users section and select your desired user.
There you can see User permissions section as in below image,

user permission image

Then, find your desired permission (ref-1) (in your case app_name|model_name|can add a new data) and click (ref-2 and ref-3), then save

NOTE: Permission assigning process is a one-time thing, so you dont have to update it every time unless you need to change/re-assign the permissions.

How to use this permission in API
in you views.py, define a view like this,

from django.contrib.auth.decorators import permission_required


@permission_required('app_name.can_add_data')
def my_view(request):
    # do something
    return HttpResponse("response")