Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use $.post with django?

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?

like image 643
ocoutts Avatar asked Mar 23 '11 15:03

ocoutts


3 Answers

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.

like image 92
mpen Avatar answered Dec 08 '22 08:12

mpen


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'));
    }
});
like image 32
vmassuchetto Avatar answered Dec 08 '22 10:12

vmassuchetto


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.

like image 33
HurnsMobile Avatar answered Dec 08 '22 10:12

HurnsMobile