Question

Before posting this i've tried every solution method posted online, including solutions on Stackoverflow and Django. (I think the reason for error perhaps is due to the fact that i'm on a newer verison of jQuery and django and most solutions are dated, using jQuery 1.9 and django 1.5.1)

Here are some URL's to solutions that don't work:

Django CSRF check failing with an Ajax POST request

How to use $.post with django?

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

Any help would be appreciated. Another possibility for error is the fact that i'm not actually sure where to place these snippets exactly. So far i've pasted everything inside the jquery on document load, i've also tried pasting the code in the very start of the .js file. (My javascript code is fragmented in chunks, some are seperate .js files and some are inline with the html being rendered with django context, so any solutions with "{{ csrftoken }}" are bad.

Thanks!!

Was it helpful?

Solution

The CSRF token only gets set if it's present in the template or if the view is decorated with ensure_csrf_cookie(). Putting {% csrf_token %} in index.html will make it apply for all your pages.

From the docs:

The CSRF token is also present in the DOM, but only if explicitly included using csrf_token in a template.

...

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

OTHER TIPS

Can you try this:

$.ajax({
            type: "POST",
            url: '{% url "some_url_which_accepts_post" %}',
            data: {'csrfmiddlewaretoken': '{{csrf_token}}', 'comment_id':1},
            success: function(data, textStatus){
                //something
            },  
        }); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top