def show(request): cart = getCart(request) item_set=[] if '_auth_user_id' in request.session: item_set=cart.cartitem_set.all() else: if cart: for album_key in cart: item=Item() item.album=album_key item.amount=cart[album_key] item_set.append(item) for item in item_set: print item.album return render_to_response('my_cart.html', { 'item_set': item_set}, context_instance=RequestContext(request))
def add_to_cart(request, album_id): cart=getCart(request) #专辑是否存在 try: album=Album.objects.get(pk=album_id) except: raise Http404 #数量是否选择 if 'amount' in request.GET: if not re.search(r'\d+$', request.GET['amount']): raise Http404 else: amount=int(request.GET['amount']) else: amount=1 #是否已有该专辑 if '_auth_user_id' in request.session: try: item = cart.cartitem_set.get(album=album) item.amount+=amount item.save() except ObjectDoesNotExist: item=CartItem.objects.create(cart=cart, album=album, amount=amount) #匿名用户购物车 else: if album in cart: cart[album]+= amount else: cart[album]=amount item=Item() item.album=album item.amount=cart[album] request.session['cart']=cart return render_to_response('new_item.html', {'item': item, 'amount': amount}, context_instance=RequestContext(request))