0

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:

enter image description here

UPDATE:

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

Community
  • 1
  • 1
agconti
  • 17,780
  • 15
  • 80
  • 114
  • have you installed the jquery cookie plugin ? One way to verify - does `alert(csrftoken)` return anything ? – karthikr Aug 21 '13 at 19:38
  • @karthikr I have jquery cookie correctly installed. executing alert(csrftoken) shows the cookie. – agconti Aug 21 '13 at 19:46
  • change the home page view to send the csrf token cookie from django.middleware.csrf import get_token def index(request): get_token(request) return render_to_response('index.html', context_instance=RequestContext(request)) – sawan gupta Aug 21 '13 at 19:52
  • @sawangupta there is no get_token module. I'm assuming you meant this `from django.core.context_processors import csrf` shown by offical docs [here](https://docs.djangoproject.com/en/dev/ref/contrib/csrf/) but putting it in the home view is not relevant to my question. – agconti Aug 21 '13 at 20:25
  • Have you imported get_token from django.middleware.csrf consider this post https://groups.google.com/forum/#!msg/dajaxproject/vszhg1hv74Q/WmkxOc7Ght4J – sawan gupta Aug 22 '13 at 17:32
  • @sawangupta Hey sawan, I dont know if your read my post or the one you linked, but I'm not using dajax (the topic in the linked post) and the linked post does not have a solution; only a question with a single comment.Thanks anyway though. – agconti Aug 22 '13 at 18:08

2 Answers2

1

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().

dan-klasson
  • 13,734
  • 14
  • 63
  • 101
  • Hey again dan, I have the token `{% csrf_token %}` in the body of my html template (not posted above) where this code is called from. The first block of code above is an external js script. I'm getting the token in that external script with `var csrftoken = $.cookie('csrftoken');` should I be getting it with `{{ csrf_token }}`? – agconti Aug 21 '13 at 19:44
  • No, you're doing it right. Inspect the value of the js variable `csrftoken`. – dan-klasson Aug 21 '13 at 20:05
  • And check the server response by adding `error: function(obj, status, err) { console.log(err); }`. – dan-klasson Aug 21 '13 at 20:11
  • From an `alert(csrftoken)` and after adding a break point and then evaluating csrftoken; I get "M96J3MrtMNvlaXN207faicFwpS9VkOb6" in the ajax post method. – agconti Aug 21 '13 at 20:11
  • And try emptying your cache. – dan-klasson Aug 21 '13 at 20:13
  • I added your error function to the end of the ajax call but how do I check the output? I am getting a new `XHR finished loading:` event in the console – agconti Aug 21 '13 at 20:16
  • I don't believe console.log is outputting the error, but several others are logged. I've updated my question with a picture so you can see what I mean. – agconti Aug 21 '13 at 20:22
  • I added an alert to the `console.log(err)` but it doesnt get called either. – agconti Aug 21 '13 at 20:27
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/35945/discussion-between-dan-klasson-and-agconti) – dan-klasson Aug 21 '13 at 20:37
0

Solution:

Empty your browser cache. The above code is correct.

agconti
  • 17,780
  • 15
  • 80
  • 114