我正在尝试为处理REST API POST请求的视图免除CSRF验证,但我仍然收到CSRF verification failed
错误。
我尝试了this question中给出的解决方案,但它没有用。
我的代码:
sendmoney REST API视图:
@api_view(["POST"])
@authentication_classes([TokenAuthentication,])
@permission_classes([IsAuthenticated, ])
@csrf_exempt
def send_money(request):
if request.method == "POST":
data = JSONParser().parse(request)
success = send_money_api(request, data)
if success["status"]:
return Response(status=status.HTTP_202_ACCEPTED)
else:
return Response({"error": success["errors"]}, status=status.HTTP_400_BAD_REQUEST)
send_money_api方法:
def send_money_api(request, data):
if data["amount"] and data["to"]:
wallet = Wallet.objects.get(username=request.user.username)
users = User.objects.all()
users_names = []
for user in users:
users_names.append(user)
if int(data["amount"]) > int(wallet.amount):
return {"status": False, "errors": "Withdraw amount greater than balance"}
elif data["to"] == "ravinkohli" and data["to"] == request.user.username and data["to"] not in users_names:
return {"status": False, "errors": "Invalid recipient"}
else:
wallet.subtract_money(data["amount"])
wallet.save()
transaction = Transaction(from_name=request.user.username, wallet_id=wallet, date=datetime.datetime.now(),
to=data['to'], amount=data["amount"])
transaction.save()
return {"status": True}
else:
return {"status": False, "errors": "Missing content"}
错误
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.
答案 0 :(得分:1)
send_money_api(...)
视图的CSRF验证失败。只需在第二个视图上方添加@csrf_exempt
装饰器。