4

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.

Aditi
  • 820
  • 11
  • 27
Vinay Guda
  • 55
  • 1
  • 1
  • 9

1 Answers1

9

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")


JPG
  • 82,442
  • 19
  • 127
  • 206
  • did you migrated after adding `permissions` to model's `Meta` class ? – JPG Feb 27 '18 at 08:52
  • If you did it properly, must be in `Permission`. It can be fetched/see either by `ORM` or `django-admin` – JPG Feb 27 '18 at 09:25
  • Thanks a lot for the reply but I'm blank right now. so can you please tell me what exactly to do? I came to know that we can execute in the shell just now. so I hope you understand my situation. – Vinay Guda Feb 27 '18 at 09:35
  • I think you didn't migrated properly. So run, `python manage.py makemigrations app_name` and then run `python manage.py migrate app_name` – JPG Feb 27 '18 at 09:38
  • I did and the problem still persists. this is my models.py http://prntscr.com/ikbvez – Vinay Guda Feb 27 '18 at 09:41
  • It's an internship project so I'm afraid I can't. but I think I can show you on TeamViewer or any software – Vinay Guda Feb 27 '18 at 09:51
  • hey!! I ran this `python manage.py migrate app_name zero` and then migrated the app then it worked. thanks a lot!! – Vinay Guda Feb 27 '18 at 10:31
  • Glad to hear that :) – JPG Feb 27 '18 at 10:32