// models.py from django.db.models.fields import FloatField class Product(models.Model): title = models.CharField(max_length=225) price = models.FloatField() discount_percent = FloatField(default=0) # Assigning it a default value of 0 so it doesn't throw a 'NoneType' error when it's null. @property def discount(self): if self.discount_percent > 0: discounted_price = self.price - self.price * self.discount_percent / 100 return discounted_price class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) # get_total function has to be updated too to calculate using the correct current price @property def get_total(self): if self.product.discount_percent > 0: price_now = self.product.price - self.product.price * self.product.discount_percent / 100 else: price_now = self.product.price total = price_now * self.quantity return total // Your template {% if product.discount_percent %} <h4 class="product__price--original">₾{{ product.price|floatformat:2 }}</h4> <h4 class="product__price--discounted">₾{{ product.discount|floatformat:2 }}</h4> {% else %} <h4>₾{{ product.price|floatformat:2 }}</h4> {% endif %} // Here's some Sass too, if you need it .product__price { &--original { text-decoration: line-through; } &--discounted { color: green; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter