Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Ajax "FORBIDDEN" error

I've seen instances where people are getting forbidden errors while attempting to make remote Ajax requests, but I'm making a local request and I also have CSRF turned on in my middleware.

errorThrown is returning "Forbidden"

I think the issue might be that I'm trying to send this to a normal view (the current page)... I'm not sure if my preprocessor is returning to the view to re-render the page.. or if it's returning right back to my current page. (don't think I explained that very well)

Hopefully this gives you a good enough picture of whats going on. Any/All help is appreciated.

the .ajax:

jQuery.ajax({
        type: "POST",
        dataType: "json",
        data: dataString,
        success: function(json) {
              jQuery(".signup").attr('disabled', false);
              $('.success').show();
              console.log(json.message);
        },
        error: function(jqXHR, textStatus, errorThrown) {
              jQuery(".signup").attr('disabled', false);
              $('.fail').show().append(errorThrown);
              console.log(textStatus);
        }

    });
like image 578
Chris Avatar asked May 30 '11 15:05

Chris


3 Answers

You need a CSRF token even if the request is to the same domain. There's code here to add a CSRF token to your AJAX requests (with jQuery):

https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#ajax

This link points to version 1.7, if you are using a different version of Django you can select your version from the floater menu on the bottom right.

like image 180
Luke Sneeringer Avatar answered Oct 01 '22 21:10

Luke Sneeringer


You will get 403 errors if you have csrf on, try adding in views.py to see if this is causing it:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
view class/method
like image 29
Oleksiy Avatar answered Oct 01 '22 22:10

Oleksiy


Well, if you still want CSRF protection, read my solution.

In my case I have a template in which I don't want to have a <form></form> element. But I still want to make AJAX POST requests using jQuery.

I got 403 errors, due to CSRF cookie being null, even if I followed the django docs (https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/). The solution is in the same page, mentioning the ensure_csrf_cookie decorator.

My CSRF cookie did get set when I added this at the top of my views.py:

from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie

Also, please note that in this case you do not need the DOM element in your markup / template: {% csrf_token %}

like image 23
scrat.squirrel Avatar answered Oct 01 '22 20:10

scrat.squirrel