Django Python:为特定用户添加自定义权限 [英] Django Python : adding custom permissions to specific users
问题描述
Models.py
class Meta:权限=(("can_add_data",可以添加新数据"),)
这是我在Models.py中创建的自定义权限,并且我还创建了这些用户.
然后,找到所需的权限( ref-1 )(在您的情况下, app_name | model_name |可以添加新数据
),然后单击( ref-2 和 ref-3 ),然后保存
注意:权限分配过程是一次性的,因此您不必每次都进行更新,除非您需要更改/重新分配权限.
如何在API中使用此权限
在您的 views.py
中,定义一个这样的视图,
导入Permission_required@permission_required('app_name.can_add_data')def my_view(要求):# 做一点事返回HttpResponse("response")
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.
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")
这篇关于Django Python:为特定用户添加自定义权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!