django 中的自定义权限不起作用

Custom permissions in django isn't working

我想添加自定义权限:

  1. 只有对象的管理员和所有者可以修改对象
  2. 所有注册用户都可以查看对象

我的解决方案:

SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS')

class IsApplicationAdmin(permissions.BasePermission):

    def has_permission(self, request, view):
        if request.user.is_authenticated:
            if request.user.is_superuser or request.user.user_type == "Admin":
                return True
            if request.method in SAFE_METHODS:
                return True

    def has_object_permission(self, request, view, obj):
        if request.method in SAFE_METHODS:
            return True

        return obj.user_name == request.user # owner can modify the object

问题 -- 对于 PATCH 请求(部分更新)http://127.0.0.1:8000/api/admin_panel/users/2/ 我有这个错误

{
    "detail": "You do not have permission to perform this action."
}

我正在调试代码,只在 has_permission 中看到调试日志(has_object_permission 中没有日志)

我应该修复什么?

我正在阅读 https://www.django-rest-framework.org/api-guide/permissions/#custom-permissions 并且 table 说 PATH 请求与对象权限相关

应按以下方式检查自定义权限和身份验证

from rest_framework import permissions  
from rest_framework.permissions import IsAuthenticated

class IsApplicationAdmin(IsAuthenticated):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS or request.user.is_superuser:
            return True
        return obj.user_name == request.user.username # I think you want to check usernames here because on left side its obj.user_name ?

请尝试使用此方法,如果有问题请告诉我。