Unable to jQuery $.post data to a view in django due to CSRF

空扰寡人 提交于 2019-12-24 12:07:39

问题


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!!


回答1:


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




回答2:


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
            },  
        }); 


来源:https://stackoverflow.com/questions/18094462/unable-to-jquery-post-data-to-a-view-in-django-due-to-csrf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!