Я пытаюсь добавить более одного товара в корзину. Я был в состоянии добавить один из каждого элемента в корзину, но когда я попытался реализовать функцию количества, я получаю эту ошибку. Когда я использовал al oop, который делал кнопки, когда я нажимал на них, это добавляло один из этих пунктов в заказ. Я хочу иметь возможность добавлять несколько одинаковых элементов. Спасибо
Views.py:
def view(request):
products = Product.objects.all()
try:
the_id = request.session['cart_id']
except:
the_id = None
if the_id:
cart = Cart.objects.get(id=the_id)
products = Product.objects.all()
context = {"cart": cart,
"products": products
}
else:
context = {"empty": True,
"products": products
}
template = "mis446/home.html"
return render(request, template, context)
def update_cart(request, slug, qty):
try:
qty = request.GET.get('qty')
update_qty = True
except:
qty = None
update_qty = False
try:
the_id = request.session['cart_id']
except:
new_cart = Cart()
new_cart.save()
request.session['cart_id'] = new_cart.id
the_id = new_cart.id
cart = Cart.objects.get(id=the_id)
try:
product = Product.objects.get(slug=slug)
except Product.DoesNotExist:
pass
except:
pass
cart_item, created = CartItem.objects.get_or_create(cart = cart, product=product)
if created:
print ("yeah")
if update_qty and qty:
if int(qty) == 0:
cart_item.delete()
else:
cart_item.quantity = qty
cart_item.save()
else:
pass
# if not cart_item in cart.items.all():
# cart.items.add(cart_item)
# else:
# cart.items.remove(cart_item)
new_total = 0.00
for item in cart.cartitem_set.all():
line_total = item.product.price * item.quantity
new_total += line_total
request.session['items_total'] = cart.products.all().count()
cart.total = new_total
cart.save()
return HttpResponseRedirect(reverse("cart"))
urls.py:
url(r'^cart/(?P<slug>[\w-]+)/$', carts_views.update_cart, name='update_cart'),
url(r'^cart/$', carts_views.view, name='cart')
models.py:
class CartItem(models.Model):
cart = models.ForeignKey('Cart', null= True, blank = True, on_delete = models.CASCADE)
product = models.ForeignKey(Product, on_delete = models.CASCADE)
quantity = models.IntegerField(default=1)
line_total = models.DecimalField(default = 10.99, max_digits = 1000, decimal_places=2)
def __unicode__(self):
try:
return str(self.cart.id)
except:
return self.product.title
class Cart(models.Model):
# items = models.ManyToManyField(CartItem, null=True, blank = True)
# products = models.ManyToManyField(Product, null=True, blank=True)
total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00)
active = models.BooleanField(default=True)
def __unicode__(self):
return "Cart id: %s" %(self.id)
html :
<label for="order"><h2 style= "color:#EAEAEA"><u>Order Details</u></h2></label>
<table class='table' style= "color:#EAEAEA">
<thead>
<th>Item</th>
<th>Price</th>
<th>Quantity</th>
<th></th>
</thead>
<tfoot>
<tr>
<th></th>
<td></td>
<td>Total: {{ cart.total }}</td>
</tr>
</tfoot>
{% for item in cart.cartitem_set.all %}
<tr><td>{{ item.product }}</td><td>{{ item.product.price }}</td><td>
<td>{{ item.quantity}}</td><td><a href='{% url "update_cart" item.product.slug %}?qty=0'>Remove</a> </tr>
{% endfor %}
</table>
</form>
{% for product in products %}
<div>
<br>
<button class ="btn btn-info btn-md" class ='pull-right'> <a href='{% url "update_cart" product.slug %}?qty=10' style= "color:#EAEAEA">{{ product.name }}: ${{ product.price }}</a></button>
<br>
<form class = 'pull-right' method ='GET' action='{% url "update_cart" product.slug %}?qty=12'>
<input name = 'qty' type = 'number'/>
<input type = 'submit' value = 'Add to cart'/>
</form>
</div>
{% endfor %}