Reputation: 18123
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.
Upvotes: 0
Views: 682
Reputation: 14220
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().
Upvotes: 1