How can I use the jquery.post()
method in Django?
This is what I am trying t开发者_C百科o 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.
The contrib
module in Django has a CSRF module that you can use.
As to your question how to send a POST
, as long as you have the URL mapped properly requests will get sent to it. You can handle a POST
request specifically by checking request.POST
on the request object.
精彩评论