[Python] Items Not Getting Added To Anonymous Users Cart?

Discussão em 'Python' iniciado por Stack, Agosto 11, 2025.

  1. Stack

    Stack Membro Participativo

    i wanna make non logged in users can added items to thier cart but when i click add to cart no item getting added to thier cart

    this is my views.py :

    from django.shortcuts import render
    from django.http import JsonResponse
    import json
    import datetime
    from .models import *

    def store(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()
    cartItems = order.get_cart_items
    else:
    #Create empty cart for now for non-logged in user
    items = []
    order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
    cartItems = order['get_cart_items']

    products = Product.objects.all()
    context = {'products':products, 'cartItems':cartItems}
    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()
    cartItems = order.get_cart_items
    else:
    #Create empty cart for now for non-logged in user
    items = []
    order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
    cartItems = order['get_cart_items']

    context = {'items':items, 'order':eek:rder, 'cartItems':cartItems}
    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()
    cartItems = order.get_cart_items
    else:
    #Create empty cart for now for non-logged in user
    items = []
    order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
    cartItems = order['get_cart_items']

    context = {'items':items, 'order':eek:rder, 'cartItems':cartItems}
    return render(request, 'store/checkout.html', context)

    def updateItem(request):
    data = json.loads(request.body)
    productId = data['productId']
    action = data['action']
    print('Action:', action)
    print('Product:', productId)

    customer = request.user.customer
    product = Product.objects.get(id=productId)
    order, created = Order.objects.get_or_create(customer=customer, complete=False)

    orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)

    if action == 'add':
    orderItem.quantity = (orderItem.quantity + 1)
    elif action == 'remove':
    orderItem.quantity = (orderItem.quantity - 1)

    orderItem.save()

    if orderItem.quantity <= 0:
    orderItem.delete()

    return JsonResponse('Item was added', safe=False)

    def processOrder(request):
    transaction_id = datetime.datetime.now().timestamp()
    data = json.loads(request.body)

    if request.user.is_authenticated:
    customer = request.user.customer
    order, created = Order.objects.get_or_create(customer=customer, complete=False)
    total = float(data['form']['total'])
    order.transaction_id = transaction_id

    if total == order.get_cart_total:
    order.complete = True
    order.save()

    if order.shipping == True:
    ShippingAddress.objects.create(
    customer=customer,
    order=order,
    address=data['shipping']['address'],
    city=data['shipping']['city'],
    state=data['shipping']['state'],
    zipcode=data['shipping']['zipcode'],
    )
    else:
    print('User is not logged in')

    return JsonResponse('Payment submitted..', safe=False)


    this my cart.js :

    var UpdateBtns= document.getElementsByClassName('update-cart')
    for(i=0;i< UpdateBtns.length;i++){
    UpdateBtns.addEventListener('click',function(){
    var productId = this.dataset.product
    var action = this.dataset.action
    console.log('productId',productId,'action',action)

    console.log('USER:',user)
    updateUserOrder(productId,action)
    })
    }

    function updateUserOrder(productId,action){
    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 checkout.html page :

    {% extends 'shop_templates/main.html' %}
    {% load static%}
    {%block content %}
    <div class="row">
    <div class="col-lg-6">
    <div class="box-element" id="form-wrapper">
    <form id="form">
    {% csrf_token %}
    <div id="user-info">
    {% if not request.user.is_authenticated %}
    <div class="form-field">
    <input required class="form-control" type="text" name="name" placeholder="Name..">
    </div>
    <div class="form-field">
    <input required class="form-control" type="email" name="email" placeholder="Email..">
    </div>
    {% endif %}
    </div>
    <div id="shipping-info">
    <hr>
    <p>shipping information :</p>
    <div class="form-field">
    <input class="form-control" type="text" name="address" placeholder="Address..">
    </div>
    <div class="form-field">
    <input class="form-control" type="text" name="city" placeholder="City..">
    </div>
    <div class="form-field">
    <input class="form-control" type="text" name="state" placeholder="State..">
    </div>
    <div class="form-field">
    <input class="form-control" type="text" name="zipcode" placeholder="Zip code..">
    </div>
    <div class="form-field">
    <input class="form-control" type="text" name="country" placeholder="Country..">
    </div>

    </div>
    <hr>
    <input id="form-button" class="btn btn-success btn-block" type="submit" value="Continue">
    </form>

    </div>
    <br>
    <div class="box-element hidden" id="payment-info">
    <small>Paypal info</small>
    <button id="payment">payment</button>
    </div>
    </div>
    <div class="col-lg-6">
    <div class="box-element">
    <a class="btn btn-outline-dark" href="{% url 'cart'%}">&#8592; Go Back</a>
    <hr>
    <h3>Order Summary</h3>
    <hr>
    {% for item in items %}
    <div class="cart-row">
    <div style="flex:2"><img class="row-image" src="{{item.product.imageURL}}"></div>
    <div style="flex:2"><p>{{item.product.product_name}}</p></div>
    <div style="flex:1"><p>{{item.product.price}}</p></div>
    <div style="flex:1"><p>{{item.quantity}}</p></div>
    </div>
    {% endfor %}
    <h5>Items : {{order.get_cart_items}}</h5>
    <h5>Cost : {{order.get_cart_total|floatformat:2}}</h5>
    </div>
    </div>
    </div>
    <script type="text/javascript">
    var csrftoken = '{{csrf_token}}'
    var shipping = '{{order.shipping}}'
    var total = '{{order.get_cart_total}}'
    var user = '{{request.user}}'

    if (shipping == false){
    document.getElementById('shipping-info').classList.add("hidden");
    }
    if(user !='AnonymousUser'){
    document.getElementById('user-info').classList.add("hidden");
    }

    if(shipping ==false && user !='AnonymousUser'){
    document.getElementById('form-wrapper').classList.add("hidden");
    document.getElementById('payment-info').classList.remove("hidden");
    }
    var form = document.getElementById('form')
    csrftoken = form.getElementsByTagName('input')[0].value
    form.addEventListener('submit',function(e){
    e.preventDefault()
    console.log('form Submitted')
    document.getElementById('form-button').classList.add("hidden")
    document.getElementById('payment-info').classList.remove("hidden")
    })
    document.getElementById('payment').addEventListener('click',function(e){
    submitFormData()

    })
    function submitFormData(){
    console.log('payment process...')
    var userFormData ={
    'name':null,
    'email':null,
    'total':total,
    }
    var shippingInfo = {
    'address':null,
    'city':null,
    'state':null,
    'zipcode':null,
    }
    if(shipping != false){
    shippingInfo.address = form.elements.address.value
    shippingInfo.city = form.elements.city.value
    shippingInfo.state = form.elements.state.value
    shippingInfo.zipcode = form.elements.zipcode.value
    }
    if(user =='AnonymousUser'){
    userFormData.name = form.elements.name.value
    userFormData.email = form.elements.email.value
    }

    console.log('shippingInfo:',shippingInfo)
    console.log('User info:',userFormData)

    var url = '/order_process'
    fetch(url,{
    method : 'POST',
    headers : {
    'Content-Type' : 'application/json',
    'X-CSRFToken' : csrftoken,
    },
    body:JSON.stringify({'form':userFormData,'shipping':shippingInfo})
    })
    .then((response) => response.json())
    .then((data) => {
    console.log('sucess',data);
    alert('Transation Completed');
    window.location.href= "{% url 'Store' %}"
    })
    }
    </script>
    {% endblock content %}


    i have problem for anonymous users when an anonymous user click add to cart items not getting added to the cart

    Continue reading...

Compartilhe esta Página