Answer the question
In order to leave comments, you need to log in
How to send csrftoken to Django server?
Good day, using jquery.ajax and django, I can not send a post request, because Forbidden (CSRF token missing or incorrect.):
ajax request
<script type="text/javascript">
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function getAjax() {
var csrftoken = getCookie('csrftoken');
alert(csrftoken);
$.ajaxSetup({
headers: {
'X-CSRF-Token': csrftoken
}
});
$.ajax({
url: "/os/detect/",
type: "POST",
data: {
os_type: "macOS"
},
success: function (msg) {
alert(msg);
},
error: function () {
alert("опять не получилось");
}
});
}
</script>
@csrf_protect
def userOS(request):
if request.is_ajax():
os_type = request.POST['os_type']
AnalyzeOS.objects.create(
os_type=os_type
)
return HttpResponse('OK')
else:
return render_to_response('os.html')
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question