【问题标题】:Django function based view allow is_active user whereas ClassBasedView does not allow is_active user基于 Django 函数的视图允许 is_active 用户,而 ClassBasedView 不允许 is_active 用户
【发布时间】:2020-06-16 00:35:49
【问题描述】:

我有 2 个视图。一种是基于函数的,另一种是基于类的。当我使用 is_active 用户调用基于函数的视图时,django 不会抛出任何错误,但是当我调用基于类的视图时,它会返回 403 错误。任何帮助都会非常重要赞赏。谢谢

from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, permission_classes

@require_POST
@permission_classes([IsAuthenticated,])
def test_function_based_view(request):
    return JsonResponse({
        'success': "True",
    })

class TestClassBasedView(APIView):

    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request):
        return JsonResponse({
            'success': "True",
        })

Django 版本 1.11.21

【问题讨论】:

  • 第一个问题:缩进是否正确?因为您在这里显示的代码绝对不是,这可能是原因。
  • 缩进是正确的,如果缩进是问题,那么 django 应用程序甚至不会运行。
  • 缩进已更新。
  • 好的。既然已经不碍事了,我建议您将 @require_POST 替换为 @api_view(('POST',)) (from rest_framework.decorators import api_view)
  • 确实如此 - api_view 是处理将函数视图转换为 APIView 的装饰器 - 实际上检查了 permission_classes。源代码:github.com/encode/django-rest-framework/blob/master/…

标签: python django django-rest-framework django-class-based-views


【解决方案1】:

问题可能不是基于类的视图返回 403 错误,而是基于函数的视图没有正确检查权限。这可能是因为@require_POST 没有考虑权限。

将基于函数的视图中的@require_POST 替换为@api_view(('POST',))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 2016-05-20
    • 2018-03-12
    • 1970-01-01
    • 2013-01-23
    相关资源
    最近更新 更多