首页 > 解决方案 > 对通用 API 视图的特定方法进行身份验证

问题描述

我已经使用ListCreateAPIViewRetrieveUpdateDestroyAPIView作为模型。现在我想将JWT身份验证添加到RetrieveUpdateDestroyAPIView. 我怎样才能做到这一点?


让我把我的问题说得更清楚一点。我有一个名为Post. 现在所有用户都可以查看帖子,但更新、删除仅对创建它的用户可用。我想使用JWT Authentication

标签: djangoauthenticationdjango-rest-framework

解决方案


您可以为此编写自定义权限类:

from rest_framework import permissions

class CustomPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        if view.action in ('update', 'destroy'):
            return request.user.is_authenticated
        return True

并在您的视图中使用:

class ExampleView(RetrieveUpdateDestroyAPIView):
    permission_classes = (CustomPermission,)

推荐阅读