Object permissions with read only access for anonymous users in Django Rest Framework

廉价感情. 提交于 2019-12-11 13:26:14

问题


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?


回答1:


The fix was actually really simple. It's possible to create a custom permissions class extending DjangoObjectPermissions, and to override the authenticated_users_only variable.

class DjangoObjectPermissionsOrAnonReadOnly(DjangoObjectPermissions):
    authenticated_users_only = False



回答2:


from rest_framework import permissions

and Just give

 permission_classes = [permissions.IsAuthenticatedOrReadOnly, YourPermissionshere, ]

in your viewset. That will do the job. if not authenticated, Anonymous users will be getting a read-only permission

you can control when the permissions are checked and not checked by handling the function

self.check_object_permissions(self.request, obj)


来源:https://stackoverflow.com/questions/39110380/object-permissions-with-read-only-access-for-anonymous-users-in-django-rest-fram

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!