How can I use the jquery.post()
method in Django?
This is what I am trying to do:
var postdata={
'username':$('#login-email').val(),
'password':$('#login-password').val()
}
$.post('/login/',postdata)
How do I CSRF protect this in django? Is there a way to add to the CSRF token to the post data?
Yes. I believe it's stored in {{ csrf_token }}
. So, just do
var postdata={
'username':$('#login-email').val(),
'password':$('#login-password').val(),
'csrfmiddlewaretoken': '{{ csrf_token }}'
}
You might have to double check the names, but that should be right.
I usually refer a file with this content to every page I want to be able to make AJAX requests:
if (!$)
var $ = django.jQuery;
$('html').ajaxSend(function(event, xhr, settings) {
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 = $.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;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
});
Although you didn't provide your html in your example is it safe to assume that you are using a <form>
? If so, add your CSRF token template tag to your form and call .serialize()
on your form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With