Django Python : adding custom permissions to specific users

百般思念 提交于 2021-02-07 09:57:40

问题


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.


回答1:


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,



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




来源:https://stackoverflow.com/questions/49003144/django-python-adding-custom-permissions-to-specific-users

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!