Django csrf in ajax POST (csrf cookie not set until {{csrf}} used)

最后都变了- 提交于 2019-12-12 01:46:32

问题


My django application uses ajax to add an item to shopping cart. The ajax request method is POST, and i enable request header via js:

var csrftoken = getCookie('csrftoken');

$.ajaxSetup({
    beforeSend: function (xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

The problem is, that i send request not from the form, but just using a button and onClick event, so i do not use a {{ csrf }} in the template. So, the cookie is not set, until i visit another page (for example, login page). Should i use a form (it is not a very good idea, because i have many items on one page, and form with csrf token is created for each one), or there is a way to set csrf cookie manually, if it is not set? Thanks.


回答1:


You can always just drop a {% csrf_token %} hidden form field anywhere in your template and pick it up by name if the cookie isn't set yet. You don't have to put it inside a form tag to be valid HTML.

Just change your logic to something like:

var csrftoken == getCookie('csrftoken') || $(":input[name='csrfmiddlewaretoken']").val();

That of course depends on what getCookie returns.



来源:https://stackoverflow.com/questions/29148666/django-csrf-in-ajax-post-csrf-cookie-not-set-until-csrf-used

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