是根据这一个教程做的
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 %}
<div class="row">
<div 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>
</div>
<div 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>
</div>
</div>
{% 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))
你的 add_product 错了,return 的位置不对