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 %}

{% for item in cart.items %} {% endfor %}
数量 名称 单价 小计
{{item.quantity}} {{item.product.title}} {{item.unit_price}} {% widthratio item.quantity 1 item.unit_price %}
总计: {{cart.total_price}} 数量: {% for item in cart.items %}{{item.quantity}}{% endfor %}

继续购物

清空购物车

结算

{% 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号