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.
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:which always works for me.
I finally made it work (based on django doc and doniyor comments)