How can I add a non-model/queryset returning view

2019-08-08 14:02发布

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条回答
家丑人穷心不美
2楼-- · 2019-08-08 15:03

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

查看更多
登录 后发表回答