无法使用 Django rest 框架提交 post 请求("detail":"CSRF Failed: CSRF token missing or incorrect.")

Can't submit a post request using Django rest framework ("detail": "CSRF Failed: CSRF token missing or incorrect.")

我遇到了一个奇怪的情况 我登录网站并尝试提交表单 如果我使用 permission_classes = [AllowAny] 或 isAuthenticate classes 我收到错误 CSRF Failed: CSRF token missing or incorrect

在下面的场景中,它会弹出一个输入密码和用户名的窗口。我的完整 class 就像

class AddReview(APIView):
    serializer_class = ReviewSerializer
    authentication_classes = (BasicAuthentication,)
    def post(self, request):  
        rest = request.POST.get('restaurant')
        dish = request.POST.get('dish')

而我的settings.py

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',

    ),
}

我只想提交一个post自定义表单来提交数据。任何使问题变得更好的帮助或建议都将受到高度赞赏。

更新

我可以使用此

提交表单
class SessionAuthentication(SessionAuthentication):
    def enforce_csrf(self, request):
        return

但为什么我必须强制执行它?我做错了什么?

理想情况下,您的网站表单应该有一个 csrf 令牌,并且该令牌也应该发送到服务器。也许是这样的:

<form method="post">{% csrf_token %}</form>
  1. CSRF中间件在MIDDLEWARE设置中默认激活。
  2. 如果你想禁用 CSRF 保护只是几个视图使用 csrf_exempt() decorator

参考资料

https://docs.djangoproject.com/en/2.2/ref/csrf/#csrf-protection-should-be-disabled-for-just-a-few-views

https://docs.djangoproject.com/en/2.2/ref/csrf/