Reputation: 85
I want to show the calculated discount under every product. The code below has no errors, but it does not display the value.
models.py:
from django.db import models
# Create your models here.
CATEGORIES = (
('Electronics', 'Electronics'),
('Clothing', 'Clothing'),
)
class Products(models.Model):
Image = models.FileField()
ProductName = models.CharField(max_length = 250, default='')
Brand = models.CharField(max_length = 250, default='')
OriginalPrice = models.IntegerField(default = '')
Price = models.IntegerField(default = '')
Category = models.CharField(max_length = 250, choices = CATEGORIES)
class Meta:
verbose_name = 'Product'
verbose_name_plural = 'Products'
def DiscountCalc(self):
Discount = (Price/OriginalPrice) * 100
return self.Discount
def __str__ (self):
return self.ProductName
This is the template index.html:
{% for product in AllProducts %}
<article class="product col-sm-3">
<a href="#" class="prodlink">
<img src="{{ product.Image.url }}" class="prodimg img-responsive">
<p class="prodname">{{ product.ProductName }}</p>
<span class="origprice">₹{{ product.OriginalPrice }}</span>
<span class="price">₹{{ product.Price }}</span>
<div class="discount">
<p>{{ product.Discount }}% off</p>
</div>
</a>
</article>
{% endfor %}
Upvotes: 0
Views: 1731
Reputation: 2061
you need to make a property :
@property
def Discount(self):
return (self.Price/self.OriginalPrice) * 100
So now you can use product.Discount :)
Docs here Django model-methods
Upvotes: 5
Reputation: 504
1)Defining a local variable and Returning a class variable will return null
2)You have to have the same name in models and template
models.py
def DiscountCalc(self):
Discount = (Price/OriginalPrice) * 100
return Discount
index.html
{% for product in AllProducts %}
<article class="product col-sm-3">
<a href="#" class="prodlink">
<img src="{{ product.Image.url }}" class="prodimg img-responsive">
<p class="prodname">{{ product.ProductName }}</p>
<span class="origprice">₹{{ product.OriginalPrice }}</span>
<span class="price">₹{{ product.Price }}</span>
<div class="discount">
<p>{{ product.DiscountCalc }}% off</p>
</div>
</a>
</article>
{% endfor %}
Upvotes: 1