I have already checked this link on Stackoverflow but still facing same issue: CSRF verification failed. Request aborted. on django
About the issue
I am trying to submit ajax request to DJango.
Html Form
<form id="frmLogin" method="post">
{% csrf_token %}
<input type="text" name="username" />
<input type="password" autocomplete="false" name="password" />
<input type="submit" value="Submit" />
</form>
Ajax
$("form#frmLogin").validate({
rules: {
username: {
required: true
},
password: {
required: true
}
},
submitHandler: function(form) {
var data = {
"username": $(form).find("input[name='username']").val(),
"password": $(form).find("input[name='password']").val(),
"csrfmiddlewaretoken": $(form).find("input[name='csrfmiddlewaretoken']").val()
};
$.ajax({
method: "POST",
url: "/authenticate/",
cache: false,
async: true,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: function(response) {
//$(form).remove();
}
})
}
});
View
from django.shortcuts import render
import json
from django.http import JsonResponse
def Authenticate(request):
if request.method == "POST":
#loginData = json.loads(request.body)
#email = userData["email"]
#password = userData["password"]
print("ok")
return JsonResponse({}, status = 200)
else:
print("not ok")
Payload Info
Error Message
Am I missing anything?
2
Answers
Following block need to be passed to add headers to make POST request successful.
You need to add
CSRF_TRUSTED_ORIGINS
insettings.py
file and add your origin to it as a trusted origin for unsafe requests like (POST request ) like this :