如何对购物车中的物品进行排序

时间:2020-10-27 00:01:53

标签: django

我正在构建一个Django电子商务网站,并且在使用购物车功能时,我注意到每次尝试更改购物车中特定商品的数量时,购物车中的所有商品都会重新排序以不同的顺序。我想知道是否有什么办法可以在后端显示项目之前对其进行排序。

**仅当用户“经过身份验证”时,我才会收到此错误**访客结帐工作正常

这是我的购物车Views.py

def cart(request):

# Authenticated Checkout
    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
        cartItems = order.get_cart_items
        items = order.orderitem_set.all()
        if cartItems == 0:
            context = {"items": items, "order": order, "cartItems": cartItems}
            return render(request, "cart_empty.html", context) 

#Guest Checkout
    else:
        data = cartData(request)
        cartItems = data["cartItems"]
        order = data["order"]
        items = data["items"]
        if cartItems == 0:
            context = {"items": items, "order": order, "cartItems": cartItems}
            return render(request, "cart_empty.html", context)

    context = {"items":items, "order": order, "cartItems":cartItems}
    return render(request, "cart.html", context)

def update_cart(request):
    data = json.loads(request.body)
    productId = data["productId"]
    action = data["action"]

   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 == "reduce":
       orderItem.quantity = (orderItem.quantity - 1)

   orderItem.save()

   if action == "remove":
       orderItem = orderItem.delete()


return JsonResponse("item was added", safe=False)

这是我的JavaScript文件

// Getting the cart cookie Value stored in the browser
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1);
    if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}

var cart = JSON.parse(getCookie("cart"));

// Finding all the Minus buttons on the page and adding a click event listener to each one
const reduce_btn = document.getElementsByClassName("btn minus1 update-cart")
for (i = 0; i < reduce_btn.length; i++) {
    reduce_btn[i].addEventListener("click", function(event){
        var productId = this.dataset.id
        var action = this.dataset.action
        if (user === "AnonymousUser"){
            addCookieItem(productId, action)
        } else {
            updateUserOder(productId,action)
        }
    })
}

// Finding all the Plus buttons on the page and adding a click event listener to each one
const increase_btn = document.getElementsByClassName("btn add1 update-cart")
for (i = 0; i < increase_btn.length; i++){
    increase_btn[i].addEventListener("click", function(event){
        var productId = this.dataset.id
        var action = this.dataset.action
        if (user === "AnonymousUser"){
            addCookieItem(productId, action)
        } else {
            updateUserOder(productId,action)
        }
    })
}

// Finding all the remove buttons on the page and adding a click event listener to each one
const removeButton = document.getElementsByClassName("removeButton")
for (i = 0; i < removeButton.length; i++) {
    removeButton[i].addEventListener("click", function(event){
        var productId = this.dataset.id
        var action = this.dataset.action
        if (user === "AnonymousUser"){
            removeFromCart(productId, action)
        } else {
            updateUserOder(productId,action)
        }
    })
}


// Removing the product from the order if the remove button is clicked
function removeFromCart(productId, action) {
    if (action == 'remove'){
        delete cart[productId];
    }
    document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/"
    location.reload()
}

// (Guest Checkout) Updating the order of the customer if he is not authenticated
function addCookieItem(productId, action) {
    console.log("not logged in..........")
    if (action == 'add'){
        cart[productId]['quantity'] += 1
    }

    if (action == 'reduce'){
        cart[productId]['quantity'] -= 1
    }
    document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/"

    location.reload()
}

// csrf token
var csrftoken = localStorage.getItem("csrftoken")


// (Authenticated Checkout) Updating the order of the customer if he is Authenticated
function updateUserOder(productId, action){
  
  var url = "http://127.0.0.1:8000/update_cart/"
  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()
  })
}

这是我的HTML文件

<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cart</title>
    <link rel="stylesheet" type="text/css" href="{% static 'css/cart.css' %}">
    <script type="text/javascript">
        var user = "{{request.user}}"
    </script>
</head>

<body>
<!-- navigation menu -->
{% include "topnav.html" %}

<div class="maincontent">
    <h1 class="hhh1" style="font-size:50px; margin:0px; margin-bottom:30px">Your Cart</h1>
    <div class="centerblock">
    <!-- DYNAMIC CONTENT GOES HERE -->
        <div class="cart-row">
            <span class="cart-item cart-header cart-column">ITEM</span>
            <span class="cart-header cart-column">PRICE</span>
            <span class="cart-quantity cart-header cart-column">QUANTITY</span>
        </div>
        <div class="cart-items">
            {% for item in items %}
            <div>
                <div class="cart-item cart-column">
                    <img class="cart-item-image" src="{{item.product.imageURL}}" width="100" height="100">
                    <span class="cart-item-title">{{item.product.title}}</span>
                </div>
                <span class="cart-price cart-column" data-price="{{item.product.price}}" >£{{item.product.price}}</span>
                <div class="cart-quantity cart-column">
                    <div class="quantity">
                        <button data-id={{item.product.id}} data-action="reduce" id="minus" class="btn minus1 update-cart" >-</button>
                        <input class="cart-quantity-input quantity" type="number" id="id_form-0-quantity" name="quantity" min="1" max="5" value="{{item.quantity}}">
                        <button data-id={{item.product.id}} data-action="add" id="plus" class="btn add1 update-cart" >+</button>
                        <button data-id={{item.product.id}} data-action="remove" class="removeButton" type="button">REMOVE</button>
                    </div>
                </div>
            </div>
            {% endfor %}
            <div class="cart-total">
                <strong class="cart-total-title">Total</strong>
                <span class="cart-total-price">£{{order.get_cart_total}}</span>
            </div>
            <div class="ordersummary">
                <form action="checkout-info" method="post">
                {% csrf_token %}
                <input type="submit" value="CHECKOUT">
                </form>
            </div>
        </div>
    </div>
</div>

{% include "footer.html" %}


<script src="{% static 'js/test2.js' %}" ></script>

</body>

</html>

1 个答案:

答案 0 :(得分:1)

假设您希望它们按照相反的顺序添加到购物车,则可以按其id字段对其进行排序:

items = order.orderitem_set.order_by('-id')