如何在创建模块时在django rest框架中的除了默认权限之外的视图集中添加自定义权限? 我有权限“fix_an_appointment”。在下面的视图集中,如何包含此权限?拥有此权限的人只能创建。
我的views.py文件:
class settingsViewSet(viewsets.ModelViewSet):
serializer_class = SettingsSerializer
queryset = Setting.objects.all()
有人可以帮忙吗?
答案 0 :(得分:3)
在ViewSet内的其他操作中,我不能使用@permission_classes(IsAuthenticated, )
这样的修饰符
要在操作中使用不同的权限,请将其作为参数放入@action()
中。
@action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf])
def set_password(self, request, pk=None):
...
答案 1 :(得分:1)
只需创建一个custom permission class
class FixAnAppointmentPermssion(permissions.BasePermission):
def has_permission(self, request, view):
return True or False
然后在您的视图集类中使用您的自定义权限
class settingsViewSet(viewsets.ModelViewSet):
serializer_class = SettingsSerializer
queryset = Setting.objects.all()
permission_classes = (FixAnAppointmentPermssion,)
答案 2 :(得分:0)
按文档custom-permissions,查看操作列表actions my_permissions.py
from rest_framework import permissions
class FixPermission(permissions.BasePermission):
"""
fix_an_appointment
"""
def has_permission(self, request, view):
if request.user.is_authenticated :
if view.action == 'retrieve':
return request.user.has_perms('fix_list_perm')
if view.action == 'retrieve':
return request.user.has_perms('fix_an_appointment')
return False
在views.py中
from my_permissions import FixPermission
class settingsViewSet(viewsets.ModelViewSet):
serializer_class = SettingsSerializer
queryset = Setting.objects.all()
permission_classes = (FixPermission,)
答案 3 :(得分:0)
我们可以为每个功能设置权限,例如创建,检索,更新,删除(添加,编辑,删除和更新)
from my_permissions import FixPermission
class FixAnAppointmentPermssion(permissions.BasePermission):
def has_permission(self, request, view):
return True or False
class YourViewSet(viewsets.ModelViewSet):
serializer_class = SettingsSerializer
queryset = Your.objects.all()
@permission_classes(FixAnAppointmentPermssion,)
def create(request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
@permission_classes(FixAnAppointmentPermssion,)
def retrive(request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)