1

The problem

I am using Django REST Framework - and so far I have been using the DjangoObjectPermissions permissions class. I use django-rules to determine which users have permissions for objects.

However, this permissions class seems to deny read access to anonymous users.

I need to find the best way to allow read-only access to all users (authenticated or not). For additions, modifications and deletions - the object permissions should be applied as normal.

What is the best approach to solving this problem? Django does not seem to provide a can_view permission by default.

Perhaps this will involve manually adding a can_view permission for each model. Or maybe it's better to somehow implement a DjangoObjectPermissionsOrAnonReadOnly permissions class?

4

2 回答 2

3

修复实际上非常简单。可以创建扩展的自定义权限类DjangoObjectPermissions,并覆盖该authenticated_users_only变量。

class DjangoObjectPermissionsOrAnonReadOnly(DjangoObjectPermissions):
    authenticated_users_only = False
于 2016-09-04T16:34:29.643 回答
1
from rest_framework import permissions

只是给

 permission_classes = [permissions.IsAuthenticatedOrReadOnly, YourPermissionshere, ]

在您的视图集中。这将完成这项工作。如果未通过身份验证,匿名用户将获得只读权限

您可以通过处理函数来控制何时检查权限和不检查权限

self.check_object_permissions(self.request, obj)
于 2016-08-24T03:02:35.640 回答