0

I'm trying to render a form through javascript in django. I tried inserting the csrf token tag through the ways described in stack overflow post How do I include Django 1.2's CSRF token in a Javascript-generated HTML form? but it did not work for me :/ I've been trying for hours to find out the reason!

var CSRF_TOKEN = document.getElementById('csrf_token').value;

for (i = 0; i < this.ShoeList.length; i++) {
html += "<form method='POST' action='/AddToCart/'>'"+CSRF_TOKEN+"'<div class = 'box'<li><img src=' " + this.ShoeList[i].imageSource + "'/>";
}

and this is my template code:

<body onload="start()">
    <input id="csrf_token" value="{{ csrf_token }}"/>
</body>

The token value is being displayed correctly when i run the code. But it does not accept the token for some reason. Please help!

Community
  • 1
  • 1

2 Answers2

0
for (i = 0; i < this.ShoeList.length; i++) {
html += "<form method='POST' action='/AddToCart/'>{% csrf_token %}<div class = 'box'<li><img src=' " + this.ShoeList[i].imageSource + "'/>";
}
0
var CSRF_TOKEN = document.getElementById('csrf_token').value;

for (i = 0; i < this.ShoeList.length; i++) {
html += "<form method='POST' action='/AddToCart/'><input type='hidden' value='"+CSRF_TOKEN+"' name='csrfmiddlewaretoken'><div class = 'box'<li><img src=' " + this.ShoeList[i].imageSource + "'/>";
}