Reputation: 99
I have the following model in my orders app:
class Order(models.Model):
# customer info
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
class OrderItem(models.Model):
order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE)
product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE)
price = models.DecimalField(max_digits=5, decimal_places=2)
quantity = models.PositiveIntegerField(default=1)
I have the following create_order view:
def create_order(request):
cart = Cart(request)
if request.method == 'POST':
form = CreateNewOrderForm(request.POST)
if form.is_valid():
order = form.save()
for item in cart:
OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity'])
cart.clear()
else:
form = CreateNewOrderForm()
PROBLEM
On creating a new order, if my cart contained multiple products, I can only see 1 (the first) product in my OrderItem.
Any advice on how to rectify this? or on where to look?
Upvotes: 0
Views: 41
Reputation: 2165
it's the identation in the line , cart.clear() , it should be out of the "for" loop
try this,
for item in cart:
OrderItem.objects.create(order=order, product=item['product'],
price=item['price'], quantity=item['quantity'])
cart.clear()
Upvotes: 1