Using ajax request in Django without form element

I want to send an ajax request (via jQuery, although I think it doesn't matter in this situation) without using the form element in Django. According to the documentation , I have to do this using the ensure_csrf_cookie decorator, however, I get Error was: cannot import name ensure_csrf_cookie .

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

I did not find much documentation on ensure_csrf_cookie , so any help would be ensure_csrf_cookie appreciated.

By the way, using @csrf_exempt works as expected.

Thanks in advance.

+3
source share
2 answers

ensure_csrf_cookie can only be a 1,4-alpha function if you have problems importing - I can import it just fine with the same statement in trunk.

The simplest solution here is to pass the csrf_token VALUE 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 looks like this ensure_csrf_cookie forces the view to set the csrf cookie, which will be needed for use in the cookie-based automatic csrf protection mechanism for the ajax jquery calls described here: https://docs.djangoproject.com/en/dev/ref/contrib/ csrf / # ajax

+6
source

You are right - this seems to be a mistake in the documentation. You should be able to use csrf_exempt instead of the same documentation page.

+1
source

Source: https://habr.com/ru/post/958566/


All Articles