购物车不起作用,我想哭

时间:2013-01-25 06:56:35

标签: python django shopping-cart

尝试为求职面试构建购物车应用。它将在几个小时后到期,我无法让它工作。

任何建议都会有所帮助 - 这是产品视图的重要组成部分:

def products(request, store_subdomain):
    store_db, store_products = database_selector(store_subdomain)
    context = RequestContext(request)
    if request.method == 'POST': #load catalog page with "item added"
        product = store_products.get(pk=request.POST['product_id'])
        cart = request.session.get('cart', {})
        if cart.get(product):
            cart['product_id'] += 1
        else:
            cart['product_id'] = 1
        request.session['cart'] = cart
    request.session.modified = True
        return render_to_response('catalog.html', 
                {'store_name': store_db.name, 'store_products': store_products, 
                'message':'Item Added'}, context_instance=context)  
    return render_to_response('catalog.html', 
        {'store_name': store_db.name, 
        'store_products' : store_products}, context_instance=context)

应添加到购物车的相关模板部分:

<form method="post" action="." class="cart">{% csrf_token %}
    {{ form.as_p }}
    <br />
    Qty <input type="number" name="qty" value = "1"> </br>
    <button type="submit" value="{{p.id}}" name= "product_id" />Add to Cart</button>
</form>

调用购物车的视图:

def shoppingcart(request, store_subdomain):
    #load page of all shopping cart items
    store_db, store_products = database_selector(store_subdomain)
    return render_to_response('shoppingcart.html', 
            {'store_name': store_db.name, 
            'store_products': store_products, 
            'cart' : cart})

应该显示购物车内容的模板:

{% for p,k in cart %}
<div class="product_image" >
        <img src="{{ STATIC_URL }}images/{{p.image}}" alt={{p.name}}/>      <br />
    </div>
    <h1><span property="v:name">{{ p.name }}</span></h1>
    <br />
    Price: {{ p.price|currency }} X Qty {{ k }} = 
{{cart}}

Post方法肯定是被触发的,但当我进入购物车页面(应该显示其中的所有产品)时,它是空的。

2 个答案:

答案 0 :(得分:1)

在请求会话中设置cart后添加以下行。

...
request.session['cart'] = cart
request.session.modified = True

默认的django行为是,如果没有更改任何属性,它就不会保存request.session,这通常是存储dict的情况。

When sessions are saved

的更多文档

答案 1 :(得分:1)

您需要将模板包装在一个块中,因为它正在扩展某些内容。您不能在{%extends%}标记之后将该代码放在那里并期望它能够正常工作。