Home > database >  django Templates sum prices of cart items
django Templates sum prices of cart items

Time:09-29

Inside DJango templates, in an HTML Page, I have the following lines of code in body.

{% for cart_data in cart_items|slice:"0:"%}
       <div >
          <div >
            <img src={{cart_data.img_url}} style="height:120px;"}} />
          </div>
          <div >
            <h1 >{{cart_data.name}}</h1>
            <h3 >{{cart_data.retailer_sku}}</h3>
            <div >
                <div >{{cart_data.color}} ({{cart_data.size}})</div>
            </div>
          </div>
          <div >
            <div >$ {{cart_data.price}}</div>

          </div>
       </div>
    {% endfor %}

This code extacts the cart items and displays them on the page.

Now I want to do is sum all the proces and show total after this loop. How to do that?

CodePudding user response:

here not possible to directly calculate sum of prices but, you can do this things with view like this

***** views.py *****

def ShowCart(request):
    usr = request.user
    product_data = Cart.objects.filter(user=usr)
    cart_count = Cart.objects.filter(user=usr).count()
    categories = CategoryModel.objects.all()
    amount = 0
    shipping_amt = 40
    final_amt = 0
    data = Cart.objects.filter(user=usr)
    for i in data:
        prod_amt = ((i.product.price)*(i.quantity))
        amount  = prod_amt
        final_amt = amount shipping_amt
    context = {'product_data': product_data, 'cart_count': cart_count,
                'prod_amt': prod_amt, 'amount': amount, 'final_amt': final_amt,
                'shipping_amt': shipping_amt,'categories':categories}

**** cart.html ****

{% for cart_data in cart_items|slice:"0:"%}
       <div >
          <div >
            <img src={{cart_data.img_url}} style="height:120px;"}} />
          </div>
          <div >
            <h1 >{{cart_data.name}}</h1>
            <h3 >{{cart_data.retailer_sku}}</h3>
            <div >
                <div >{{cart_data.color}} ({{cart_data.size}})</div>
            </div>
          </div>
          <div >
            <div >$ {{cart_data.price}}</div>

          </div>
       </div>
    {% endfor %}


 <div >
    <div >The Total Amount of </div>
    <table >
      <tbody>
        <tr>
          <td>Amount</td>
          <td >₹ {{amount}}</td>
        </tr>
        <tr>
          <td>Shipping</td>
          <td >₹ {{shipping_amt}}</td>
        </tr>
        <tr>
          <td><strong>Total</strong>(Including VAT)</td>
          <td ><strong>₹ {{final_amt}}</strong></td>
        </tr>

      </tbody>
    </table>
    <a  href="{% url 'checkout' %}">Checkout</a>
  </div>
  • Related