简体   繁体   中英

Ajax post to Django view CSRF forbidden

The problem

CSRF is preventing me from posting to a Django view.

I'm following a solution from the official django docs and this question: Django CSRF check failing with an Ajax POST request . Everything should be setup fine but it fails when it executes.

My setup is as follows,

jQuery post method:

var send_data = { 'name': place.name, 'address': address};

var csrftoken = $.cookie('csrftoken'); 

function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
} 

$.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

$.ajax({ url: '/results/',
    type: 'POST',
    data: send_data,
    success: function(response) {
      $('#results').html(response);
    }
  });

Django view:

def results(request):
    return render(request, "stamped/restaurant.html")

Urls.py

urlpatterns = patterns('',
    url(r'^$', views.home, name='home'),
    url(r'results/', views.results, name='results'),
)

Everything should be fine. Any idea on what I'm missing?

Ive also tired:

Unable to jQuery $.post data to a view in django due to CSRF

Jquery Ajax Post to Django View

Error output:

在此处输入图片说明

UPDATE:

The code in this question is correct. It seems my browser cache needed to be emptied.

In your question you're missing the template tag {{ csrf_token }} in your template.

From the docs:

If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie().

Solution:

Empty your browser cache. The above code is correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM