DjangoModelPermissions

DjangoModelPermissions

我在玩djangorestframework,我的目标是在对DjangoModelPermissions请求作出 react 的 View 上使用GET。官方文件说:



Source

所以我像下面这样修改了我的模型:

class User(AbstractUser):
    display_name = models.CharField(_('Display Name'), blank=True, max_length=255)

    class Meta:
        permissions = (
            ("view_user", "Can view users"),
        )

    def __str__(self):
        return self.username

和 View :
class UserListAPIView(ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = (permissions.DjangoModelPermissions,)

设定值:
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissions'
    ]
}

问题是我实现的UserListAPIView成功地将所有对象的列表返回给不属于Group的用户,而该用户也没有任何自定义User Permission。在我看来,DjangoModelPermissions不起作用。

最佳答案

哎呀,这比我想象的要容易:

class CustomDjangoModelPermission(permissions.DjangoModelPermissions):

    def __init__(self):
        self.perms_map = copy.deepcopy(self.perms_map)  # from EunChong's answer
        self.perms_map['GET'] = ['%(app_label)s.view_%(model_name)s']

关于python - Django Rest Framework在ListAPIView上使用DjangoModelPermissions,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46584653/

10-12 18:13