I am trying to exempt CSRF validation for a view that handles a REST API POST request, but I am still getting a CSRF verification failed
error.
I tried the solution given in this question and it did not work.
My code:
sendmoney REST API view:
@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 method:
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"}
Error
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.
The CSRF validation fails for the
send_money_api(...)
view. Simply add the@csrf_exempt
decorator above the second view too.