I am new to django and i am building an ecommerce website. When i try to make a new order in my website i got this error: NOT NULL constraint failed:orders_order.user_id
each user can have multiple orders and i want to show the orders in the users profile but i am having problem with placing orders
models.py
class Order(models.Model):
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
address = models.CharField(max_length=250)
postal_code = models.CharField(max_length=11)
city = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
class Meta:
ordering = ('-created',)
def __str__(self):
return f'Order {self.id}'
def get_total_cost(self):
return sum(item.get_cost() for item in self.items.all())
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=10, decimal_places=2)
quantity = models.PositiveIntegerField(default=1)
def __str__(self):
return str(self.id)
def get_cost(self):
return self.price * self.quantity
forms.py
class OrderCreateForm(forms.ModelForm):
class Meta:
model = Order
fields = ['address', 'postal_code', 'city']
views.py
def order_create(request):
cart = Cart(request)
if request.method == 'POST':
user = request.user
form = OrderCreateForm(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'])
context = {
'order': order,
}
# clear the cart
cart.clear()
return render(request, 'order/created.html', context)
else:
form = OrderCreateForm()
context = {'cart': cart,
'form': form,
}
return render(request, 'order/create.html', context)
template
{% extends 'shared/_MainLayout.html' %}
{% block content %}
<h1>Checkout</h1>
<div >
<h3>Your order</h3>
<ul>
{% for item in cart %}
<li>
{{ item.quantity }}x {{ item.product.name }}
<span>${{ item.total_price }}</span>
</li>
{% endfor %}
</ul>
<p>Total: ${{ cart.get_total_price }}</p>
</div>
<form method="post" >
{{ form.as_p }}
<p><input type="submit" value="Place order"></p>
{% csrf_token %}
</form>
{% endblock %}
CodePudding user response:
OrderCreateForm is used to create an order but you didn't specify user field so you should add user object to Order before saving it at views.py when you call form.save() it tries to create Order object but there is no user for this order and that's why you get NOT NULL constraint failed:orders_order.user_id
CodePudding user response:
problem solved: in views.py it should be like this:
order = form.save(commit=False)
order.user = request.user
order.save()