csrf token issue with multiple templates

我只是一个虾纸丫 提交于 2020-01-06 13:52:37

问题


I've got a template (index.html. It extends base.html) containing a form with a csrf_token wich works good. I use JS/Ajax to send data to my view. So no problem with that.

The issue is that if i copy/paste my form to another template (for example : new.html wich also extends base.html) i get : CSRF token missing or incorrect error. (HTTP 403 error in console)

Both templates use same JS function. The forms are exactly the same in both templates.

Any suggestion please?

Here the form (same in index.html and new.html) :

<form method="post" action="." enctype="multipart/form-data">
{% csrf_token %}
    <a href="#" class="heart pull-right" onclick="return Favorite(this)" data="foobar">
        <i class="fa fa-heart-o"></i>
    </a>
</form>

Here the JS/Ajax function :

function Favorite(item) {
    song_id = item.getAttribute("data"),
    $.ajax({
        type : "POST",
        datatype: "json",
        url: "/fav/",
        data: {
            'csrfmiddlewaretoken' : $('input[name=csrfmiddlewaretoken]').val(),
            song_id : song_id
        },
    });
    return false

By the way, the form in index.html is in a div. In new.html the form is in a table. Don't know if it helps.


回答1:


first of all, you dont need <form> at all if you are sending the request with ajax.

secondly, you can set the csrf_token also in this way:

...
data: {
    csrfmiddlewaretoken: '{{ csrf_token }}',
    song_id : song_id
},
...

which always works for me.




回答2:


I finally made it work (based on django doc and doniyor comments)

function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
        }
    }
}
return cookieValue;
}

function Favorite(item) {
  song_id = item.getAttribute("data-mp3"),
  csrftoken = getCookie('csrftoken');
  $.ajax({
    type : "POST",
    datatype: "json",
    url: "/fav/",
    data: {
      song_id : song_id
    },
    headers: {
      'X-CSRFToken': csrftoken
    }
  });
  return false;
}


来源:https://stackoverflow.com/questions/26702551/csrf-token-issue-with-multiple-templates

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