python - 用django做购物车,为什么购物车中相同的物品不能合并成一个?
PHP中文网
PHP中文网 2017-04-17 15:44:52
[Python讨论组]

是根据这一个教程做的
http://www.cnblogs.com/holbrook/archive/2012/03/02/2357343.html

view_cart.html

{% extends "base.html" %} {% block title %} 我的购物车{% endblock %} {% block pagename %} 我的购物车 {% endblock %} {% block content %}
<p class="row">
  <p class="span10">
    <table class="condensed-table">
      <thead>
        <tr>
          <th class="header">数量</th>
          <th class="yellow header">名称</th>
          <th class="blue header">单价</th>
          <th class="green header">小计</th>
        </tr>
      </thead>
      <tbody>
        {% for item in cart.items %}
        <tr>
          <th>{{item.quantity}}</th>
          <td>{{item.product.title}}</td>
          <td>{{item.unit_price}}</td>
          <td>{% widthratio item.quantity 1 item.unit_price %}</td>
        </tr>
        {% endfor %}
        <tr>
          <th></th>
          <td></td>
          <th>总计:</th>
          <th>{{cart.total_price}}</th>
          <th>数量:</th>
          <th>{% for item in cart.items %}{{item.quantity}}{% endfor %}</th>
        </tr>
      </tbody>
    </table>
  </p>
  <p class="span4">
    <p><a class="btn primary span2" href="#">继续购物</a></a>
    </p>
    <p><a class="btn danger span2" href="{% url 'depotapp:clean_cart'%}">清空购物车</a>
    </p>
    <p><a class="btn success span2" href="#">结算</a>
    </p>
  </p>
</p>
{% endblock %}

views.py :

def view_cart(request):
    cart = request.session.get("cart",None)
    t = get_template('depotapp/view_cart.html')
    if not cart:
        cart = Cart()
        request.session["cart"] = cart
    c = RequestContext(request,locals())
    return HttpResponse(t.render(c))

models.py

class Cart(object):
    def __init__(self, *args, **kwargs):
        self.items = []
        self.total_price = 0
    def add_product(self,product):
        self.total_price += product.price
        for item in self.items:
            if item.product.id == product.id:
                item.quantity += 1
        return self.items.append(LineItem(product=product,unit_price=product.price,quantity=1))    

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(2)
怪我咯

你的 add_product 错了,return 的位置不对

        def add_product(self,product):
            self.total_price += product.price
            for item in self.items:
                if item.product.id == product.id:
                    item.quantity += 1
                    return
            self.items.append(LineItem(product=product,unit_price=product.price,quantity=1)) 
天蓬老师

请问一下,你现在还有这个教程的源代码吗?我现在也在根据这个教材做,可是也遇到了好多问题

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号