Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango CSRF check failing with an Ajax POST request
    primarykey
    data
    text
    <p>I could use some help complying with Django's CSRF protection mechanism via my AJAX post. I've followed the directions here:</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/contrib/csrf/" rel="noreferrer">http://docs.djangoproject.com/en/dev/ref/contrib/csrf/</a></p> <p>I've copied the AJAX sample code they have on that page exactly:</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax" rel="noreferrer">http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax</a></p> <p>I put an alert printing the contents of <code>getCookie('csrftoken')</code> before the <code>xhr.setRequestHeader</code> call and it is indeed populated with some data. I'm not sure how to verify that the token is correct, but I'm encouraged that it's finding and sending something.</p> <p>But Django is still rejecting my AJAX post.</p> <p>Here's my JavaScript:</p> <pre><code>$.post("/memorize/", data, function (result) { if (result != "failure") { get_random_card(); } else { alert("Failed to save card data."); } }); </code></pre> <p>Here's the error I'm seeing from Django:</p> <blockquote> <p>[23/Feb/2011 22:08:29] "POST /memorize/ HTTP/1.1" 403 2332</p> </blockquote> <p>I'm sure I'm missing something, and maybe it's simple, but I don't know what it is. I've searched around SO and saw some information about turning off the CSRF check for my view via the <code>csrf_exempt</code> decorator, but I find that unappealing. I've tried that out and it works, but I'd rather get my POST to work the way Django was designed to expect it, if possible.</p> <p>Just in case it's helpful, here's the gist of what my view is doing:</p> <pre><code>def myview(request): profile = request.user.profile if request.method == 'POST': """ Process the post... """ return HttpResponseRedirect('/memorize/') else: # request.method == 'GET' ajax = request.GET.has_key('ajax') """ Some irrelevent code... """ if ajax: response = HttpResponse() profile.get_stack_json(response) return response else: """ Get data to send along with the content of the page. """ return render_to_response('memorize/memorize.html', """ My data """ context_instance=RequestContext(request)) </code></pre> <p>Thanks for your replies!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload