Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ajax request in Django without form element

I'd like to send an ajax request (via Jquery, although I think that's irrelevant in this situation) without using a form element in Django. According to the documentation, I should be able to do that by using the ensure_csrf_cookie decorator, however, I get Error was: cannot import name ensure_csrf_cookie.

I'm using the following import from django.views.decorators.csrf import ensure_csrf_cookie.

I didn't find a great deal of documentation about ensure_csrf_cookie, so any help will be greatly appreciated.

By the way, using @csrf_exempt works as expected.

Thanks in advance.

like image 230
Robert Smith Avatar asked Nov 05 '11 04:11

Robert Smith


People also ask

Does AJAX require a form?

No, there is no need to wrap input (or other) elements in form tags when using ajax. However, there are times when using a form construct is a good idea, such as if you want to use . serialize() to grab all the form names/values in one go (for example, if you are using ajax - it's a great shortcut).

How send data from AJAX to Django?

To send and receive data to and from a web server, AJAX uses the following steps: Create an XMLHttpRequest object. Use the XMLHttpRequest object to exchange data asynchronously between the client and the server. Use JavaScript and the DOM to process the data.

Is AJAX request GET or POST?

GET vs POST in AJAX callsUnless you are sending sensitive data to the server or calling scripts which are processing data on the server it is more common to use GET for AJAX calls. This is because when using XMLHttpRequest browsers implement POST as a two-step process (sending the headers first and then the data).


2 Answers

ensure_csrf_cookie may only be a 1.4 alpha feature if you're having trouble importing it -- I can import it just fine with the same statement on trunk.

The simplest solution here is to pass the csrf_token VALUE in the ajax call itself.

You said you were using jQuery.

    $.ajax({
        url: "",
        type: 'POST',
        data: {
             csrfmiddlewaretoken: '{{ csrf_token }}' // just the token value
        },
        success: function(response) {
        }
    })

It appears this ensure_csrf_cookie forces the view to set the csrf cookie that would be required for use in the automatic cookie based csrf protection mechanism for jquery ajax calls described here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

like image 74
Yuji 'Tomita' Tomita Avatar answered Sep 30 '22 14:09

Yuji 'Tomita' Tomita


You're right - this appears to be a bug in the documentation. You should be able to use csrf_exempt instead (same documentation page).

like image 42
shacker Avatar answered Sep 30 '22 14:09

shacker