How can I add a non-model/queryset returning view with django-restframework when using DjangoObjectPermissions?

扶醉桌前 提交于 2019-12-11 12:03:54

问题


I have a view that I want to add to my django-restframework api that does not relate to any model. Though I'm using 'rest_framework.permissions.DjangoObjectPermissions' in DEFAULT_PERMISSION_CLASSES.

class EnumChoices(views.APIView):       
    def get(self, request):
        enums = {}
        return Response(enums)

Now Django complains about my view:

AssertionError at /api/enums/
Cannot apply DjangoModelPermissions on a view that does not have `.queryset` property or overrides the `.get_queryset()` method.

I need the permission class for almost all other views and do not want to get rid of it. How can I get around the mandatory attributes for the one view?


回答1:


You can add a view-specific permission logic to overwrite the model permission check. Create a BasePermission class object and add it to your views permission_classes attribute. Don't forget IsAuthenticated unless you want to allow anonymous users too.

class EnumChoices(views.APIView):
    class EnumPermission(permissions.BasePermission):
        def has_permission(self, request, view):
            # whatever permission logic you need, e.g.
            return request.user.has_perm("planning.view_enums")
    permission_classes = (permissions.IsAuthenticated, EnumPermission)

    def get(self, request):
        enums = {}
        return Response(enums)

Now the view will ensure the user is authenticated and has the view_enums permission.

More info here: http://www.django-rest-framework.org/api-guide/permissions/#custom-permissions



来源:https://stackoverflow.com/questions/34040069/how-can-i-add-a-non-model-queryset-returning-view-with-django-restframework-when

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