How to use $.post with django?

ocoutts picture ocoutts · Mar 23, 2011 · Viewed 12.5k times · Source

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?

Answer

mpen picture mpen · Mar 23, 2011

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.