問題描述
購物車不工作,我想哭 (Shopping cart won't work and I want to cry)
Trying to build a shopping cart app for a job interview. It's due in a few hours and I can't get it to work.
Any suggestions would be helpful‑‑here's the product view that does the heavy lifting:
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)
And the relevant template portion that should add to the cart:
<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>
And the view which calls the cart:
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})
And the template which should display what's in the 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}}
The Post method is definitely being triggered, but when I go to the shopping cart page (which should show all the products in it) it's empty.
‑‑‑‑‑
參考解法
方法 1:
Add following line after you set the cart
in the request session.
...
request.session['cart'] = cart
request.session.modified = True
Default django behavior is it would not save request.session
if any of its attribute is not changed, which is generally case when dict is stored.
More documentation at When sessions are saved
方法 2:
You need to wrap the template in a block since it's extending something. You can't just put that code in there after an {% extends %} tag and expect it to work.
(by thumbtackthief、Rohan、Stavros Korokithakis)