Search code examples
djangojquerydjango-csrf

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?


Solution

  • 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'));
        }
    });