如果我可能有错误的代码,我很抱歉,但我并没有真正做太多的 django 休息。我想检测 django 内置用户模型的权限。我向用户模型添加了权限,但由于某种原因 has_perm 不起作用。我改为使用 user_objects.all() 并检测权限对象是否存在。如果用户没有权限,我想返回错误 400: Unauthorized。
这是我当前的解决方案(不起作用):
class ProgramListCreateView(PermissionRequiredMixin,ListCreateAPIView):
permission_required = Permission.objects.get(name="Can CRUD")
permission_classes = (IsAuthenticated,)
queryset = Program.objects.all()
serializer_class = ProgramSerializer
def check_user(self,request):
if self.permission_required in request.user.user_permissions.all():
return True
return Response(status=400)
当我在未经许可的情况下发送带有用户 token 的 json 时,它仍然会创建对象
这是我的混音:
class PermissionRequiredMixin(object):
user_check_failure_path = 'auth_login'
permission_required = None
def check_user(self, user):
return user.has_perm(self.permission_required)
注意:由于某种原因,has_perm 总是返回 false,即使我使用 user.user_permissions.add(permission_object) 添加它
最佳答案
听起来您正在尝试验证特定用户是否有权访问您的 APIView
。
您可以简单地使用DjangoModelPermissions
read more
class ProgramListCreateView(ListCreateAPIView):
permission_classes = (IsAuthenticated, DjangoModelPermissions)
...
您还可以使用自定义权限read more
from rest_framework import permissions
class UserPermission(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
'''
Object-level permission to only allow user model manipulation
'''
# IF you would like to allow GET, HEAD or OPTIONS requests,
if request.method in permissions.SAFE_METHODS:
return True
# check if user is owner
return request.user == obj
使用
from custom_permission import UserPermission
class ProgramListCreateView(ListCreateAPIView):
permission_classes = (UserPermission, )
...
或
如果您想在全局范围内授予您的权限,您可以将其包含在您的settings.py中
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
'rest_framework.permissions.DjangoModelPermissions',
)
}
关于python - 权限混入 Django REST ListCreateAPIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47185334/