Estoy tratando de crear un carrito de compras para mi sitio web usando java script y django. Pero cuando hago clic en el botón "agregar al carrito", aparece un error Error de referencia no detectado: csrftoken no está definido en updateUserOrder (cart.js: 28:19) en HTMLButtonElement. (cart.js:14:13) en la consola, que hace referencia al código X-CSRFToken: csrftoken. archivo cart.js:
var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function () { var productId = this.dataset.stuff var action = this.dataset.action console.log('productId:', productId, 'Action:', action) console.log('USER:', user) if (user == 'AnonymousUser') { console.log('User is not authenticated') } else { updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log('User is authenticated, sending data...') var url = '/update_item/' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) => { return response.json(); }) .then((data) => { location.reload() }); }base.html:
<script type="text/javascript" src="{% static 'js/cart.js' %}">var user = '{{request.user}}' function getToken(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // 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; } var csrftoken = getToken('csrftoken') </script> {% endblock content %}botón:
<button data-stuff="{{stuff.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button>