试图为求职面试构建一个购物车应用程序。几个小时后就要到期了,我不能让它工作。
任何建议都会有所帮助——这是完成繁重工作的产品视图:
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 方法肯定会被触发,但是当我转到购物车页面(应该显示其中的所有产品)时,它是空的。