CSRF验证失败。请求中止,失败原因是未设置CSRF cookie

时间:2019-09-19 10:22:06

标签: django django-rest-framework django-views

我想实现我网站的登录。我基本上遵循了在线教程,并且遵循相同的确切方法。但是,在提交注册表格时,我仍然遇到错误(CSRF验证失败。请求被中止。)有人可以告诉我是什么引发了该错误以及如何解决该错误吗?

这是我的代码:

from django.shortcuts import render
from rest_framework.status import (
    HTTP_400_BAD_REQUEST,
    HTTP_404_NOT_FOUND,
    HTTP_200_OK
)
from rest_framework import status,views
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.contrib.auth import authenticate,login,logout
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Token
from rest_framework.decorators import permission_classes
from rest_framework.permissions import AllowAny


@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
def login(request):
    username = request.data.get("username")
    password = request.data.get("password")
    if username is None or password is None:
        return Response({'error': 'Please provide both username and 
password'},
                    status=HTTP_400_BAD_REQUEST)
user = authenticate(username=username, password=password)
if not user:
    return Response({'error': 'Invalid Credentials'},
                    status=HTTP_404_NOT_FOUND)
token, _ = Token.objects.get_or_create(user=user)
return Response({'token': token.key},
                status=HTTP_200_OK)

获取输出:

Forbidden (403)

CSRF verification failed. Request aborted.

You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.

 If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests.

1 个答案:

答案 0 :(得分:1)

string numberOfTablesText = "..."; List<string> tableNames = new List<string>(); 告诉您尽管该网站需要一个视图,但不要寻找@csrf_exempt。从视图中删除csrf_token,然后在模板中将@csrf_exempt传递到表单中,即

{% csrf_token %}