Raise ValueError( ValueError: Cannot assign "'TJFIDEL2401'": "Order.discount_code" must be a "DiscountCode" instance

I'm trying to implement a checkout page using Django framework. I have DiscountCode model linked to the Order model as "discount_code = models.ForeignKey(DiscountCode, on_delete=models.SET_NULL, null=True, blank=True)". When I proceed to click on the place order button on the checkout page, an error message occurs that is, "raise ValueError(ValueError: Cannot assign "''": "Order.discount_code" must be a "DiscountCode" instance." - I have spent already a couple of hours trying to resolve this issue. The problem occurs when the form.is_valid() is triggered

Models: class DiscountCode(models.Model): code = models.CharField(max_length=50, unique=True) # Unique discount code discount_amount = models.DecimalField(max_digits=5, decimal_places=2) # e.g., 10.00 for a fixed amount discount discount_percent = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) # e.g., 10.00% for percentage discount valid_from = models.DateTimeField() valid_until = models.DateTimeField() max_uses = models.PositiveIntegerField(default=1) # Number of times the discount can be used users = models.ManyToManyField(Account, blank=True) # Assign to specific users or leave empty for all users is_active = models.BooleanField(default=True) # Active status def __str__(self): return self.code def is_valid(self): now = timezone.now() return self.is_active and self.valid_from <= now <= self.valid_until and self.max_uses > 0 class Order(models.Model): STATUS_CHOICES = ( ('New', 'New'), ('Processing', 'Processing'), ('Shipped', 'Shipped'), ('Delivered', 'Delivered'), ('Cancelled', 'Cancelled'), ) user = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True) payment = models.ForeignKey(Payment, on_delete=models.SET_NULL, blank=True, null=True) discount_code = models.ForeignKey(DiscountCode, on_delete=models.SET_NULL, null=True, blank=True)

Вернуться на верх