0
votes

I try to runserver and it runs but my chrome console identifies error at headers and it does npt execute the add to cart.

I have refreshed my page several times. P have even turned off my server and ran my server multiple times but same issues remain.

My csrf token is defined in my main.html

<!DOCTYPE html>
{% load static %}
<html>
<head>
    <title>Ecom</title>

 <link rel="stylesheet" 

href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1" />

 <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}">

 <script type="text/javascript">
    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 tis cookie string begin with the name we want? if not we can change it
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue
    }
    var csrftoken = getToken('csrftoken')
 </script>

My Cart.js File

var updateBtns = document.getElementsByClassName('update-cart')


for (var i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function(){
    var productId = this.dataset.product
    var action = this.dataset.action
    console.log('productId:',productId, 'action:',action)

    console.log('USER:',user)
    if (user === 'AnonymousUser') {
        console.log('user is not logged in')
    }else{
        updateUserOrder(productId, action)
    } 
})

}

function updateUserOrder(productId, action){
console.log('user is logged in, 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) =>{
    console.log('data:', data)
})

}

This is my views.py which does not execute on my console

My views.py

from django.shortcuts import render

from django.http import JsonResponse
import json

from .models import *
# Create your views here.


def store(request):
    products = Product.objects.all()
    context = {'products':products}
    return render(request, 'store/Store.html', context)

def cart(request):
    if request.user.is_authenticated:
    customer = request.user.customer
    order, created = Order.objects.get_or_create(customer=customer, complete=False)
    items = order.orderitem_set.all()
else:
    items = []
    order = {'get_cart_total':0, 'get_cart_items':0}
context = {'items':items, 'order':order}
return render(request, 'store/Cart.html', context)

def checkout(request):
    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
        items = order.orderitem_set.all()
    else:
        items = []
        order = {'get_cart_total':0, 'get_cart_items':0}
    context = {'items':items, 'order':order}

    return render(request, 'store/Checkout.html', context)

def updateItem(request):
    data = json.loads(request.data)
    productId = data['productId']
    action = data['action']

    print('Action:', action)
    print('productId:', productId)
    return JsonResponse('item added to cart', safe=False)![enter image description here](https://i.stack.imgur.com/zOztb.jpg)
1
Where did you define the csrftoken token? - Sumithran
in my main.html - swift

1 Answers

0
votes

your fetch syntax should have a comma(,) after the method and headers

the correct syntax is method: "POST", headers: {.....}, body:JSON.stringify({....})