gpt4 book ai didi

python - Django Rest Framework 在 ListAPIView 上使用 DjangoModelPermissions

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:36 24 4
gpt4 key购买 nike

我正在使用 djangorestframework,我的目标是在我的 View 上使用 DjangoModelPermissions,它对 GET 请求使用react。官方文档说:

The default behavior can also be overridden to support custom model permissions. For example, you might want to include a view model permission for GET requests.

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权限。在我看来,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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com