我如何添加一个非模式/查询集使用DjangoObjectPermissions时Django的restframework返回看法? [英] How can I add a non-model/queryset returning view with django-restframework when using DjangoObjectPermissions?

查看:547
本文介绍了我如何添加一个非模式/查询集使用DjangoObjectPermissions时Django的restframework返回看法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我想要添加到我的Django的restframework API,它并不涉及任何模型的视图。虽然我在DEFAULT_PERMISSION_CLASSES使用rest_framework.permissions.DjangoObjectPermissions。

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)

现在的Django抱怨我的看法:

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?

推荐答案

您可以添加视图特定权限的逻辑覆盖模型权限检查。创建一个BasePermission类对象,并把它添加到你的观点permission_classes属性。除非你想允许匿名用户也不要忘记IsAuthenticated。

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)

现在的观点将确保用户进行身份验证并具有view_enums许可。

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

此处了解详情:的http://www.django-rest-framework.org/api-guide/permissions/#custom-permissions

这篇关于我如何添加一个非模式/查询集使用DjangoObjectPermissions时Django的restframework返回看法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆