I have a simple e-commerce app, and I'm trying to clear the cart after pressing the 'Proceed to checkout' button. After pressing it I should redirect to cart and I shouldn't see any OrderItem in the cart. Also the database instance should be deleted. How can I do?
store/models.py
class Item(models.Model):
name = models.CharField(max_length=50)
price = models.FloatField()
def __str__(self):
return self.name
class OrderItem(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField(default=1)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
ordered = models.BooleanField(default=False)
def __str__(self):
return f"{self.quantity} of {self.item.name}"
def get_total_item_price(self):
return self.quantity*self.item.price
def get_final_price(self):
return self.get_total_item_price()
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
items = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now=True)
ordered_date = models.DateTimeField()
ordered = models.BooleanField(default=False)
def __str__(self):
return self.user.username
def get_total(self):
total = 0
for order_item in self.items.all():
total = order_item.get_final_price()
return total
store/views.py
class HomepageView(generic.ListView):
model = Item
template_name= 'store/index.html'
context_object_name = 'item_list'
class DetailView(generic.DetailView):
model = Item
template_name='store/detail.html'
class CartView(generic.View):
def get(self, *args, **kwargs):
try:
order = Order.objects.get(user=self.request.user, ordered=False)
context = {
'object': order
}
return render(self.request, 'store/cart.html', context)
except ObjectDoesNotExist:
messages.warning(self.request, "You do not have an active order")
return redirect("/")
def checkout(request, user_id):
#code to remove all items from cart
return redirect('store:cart', user_id=user_id)
CodePudding user response:
If you just set order.ordered = True
in your checkout
function, then the cart query will not be valid, thus clearing the cart, and you can keep the order in your records. I do not suggest outright deleting the object.
CodePudding user response:
I hope you're getting everything in cart by the below query
order = Order.objects.get(user=self.request.user, ordered=False)
So, you can delete the cart using same query with delete()
as below
Order.objects.get(user=self.request.user, ordered=False).delete()
CodePudding user response:
checkout() function after @DanielOdicho suggestion:
def checkout(request, pk):
order = get_object_or_404(Order, pk=pk)
order.ordered = True
order.save()
return redirect('store:cart', user_id=request.user.id)
It works!