问题描述
限时送ChatGPT账号..我有一个视图要添加到我的 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/api-guide/permissions/#custom-permissions
这篇关于使用 DjangoObjectPermissions 时,如何使用 django-restframework 添加非模型/查询集返回视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论