Django: Cancel Order functionality not updating CartOrder and CartOrderItems instances

I'm building an e-commerce application using Django, and I'm having trouble with the cancel order functionality. When a user cancels an order, I want to update the product_status field of both the CartOrder and CartOrderItems instances to "cancelled". However, the update is not happening, and I'm not seeing any error messages.

Here's my code:

models.py:

class CartOrder(models.Model):  
   # ...  
   product_status = models.CharField(choices=STATUS_CHOICE, max_length=30, default="processing")  
  
class CartOrderItems(models.Model):  
   # ...  
   product_status = models.CharField(max_length=200, blank=True, null=True)  
   order = models.ForeignKey(CartOrder, on_delete=models.CASCADE, related_name="cartorderitems")

views.py:

def create_cancel(request, oid):  
   if request.method == "POST":  
      user = request.user  
  
      try:  
        # Fetch the CartOrder instance  
        order = get_object_or_404(CartOrder, id=oid)  
        order.product_status = "cancelled"  
        order.save()  
  
        # Fetch the related CartOrderItems instance  
        order_item = order.cartorderitems.first()  
        order_item.product_status = "cancelled"  
        order_item.save()  
  
        # Fetch the associated product  
        product = get_object_or_404(Product, pid=order.pid)  
  
        # Additional product-related operations can be done here, if needed  
        messages.success(request, "Order successfully cancelled.")  
  
      except Exception as e:  
        messages.error(request, f"An error occurred: {e}")  
  
      return redirect("core:dashboard")  
   else:  
      messages.error(request, "Invalid request method.")  
      return redirect("core:dashboard")

I've tried using order.cartorderitems.first() and CartOrderItems.objects.filter(order=order).first() to get the related CartOrderItems instance, but neither approach is working.

Can anyone help me figure out what's going wrong? I've checked the database, and the product_status field is not being updated for either the CartOrder or CartOrderItems instances.

Back to Top