I have model called product in which i have expiry date as DateFiled, i need to calculate number of days left for expiry for all the products and display the product name and number of days left for expiry of every products from product table.
class Product(models.Model):
category = models.ForeignKey('store.Category',on_delete=models.CASCADE,default='SYRUP')
itemname = models.CharField(max_length=50,blank=True,null=True)
itemexpdate = models.DateField(auto_now_add=False, auto_now=False,blank=True,null=True)
class Category(models.Model):
name = models.CharField(max_length=200,blank=True)
def days_left_for_expiry(expiry_date):
today = date.today()
expiry = expiry_date
delta = expiry - today
return str(delta.days)
def home(request):
d = Product.objects.all()
for product in d:
expiry_date = product.itemexpdate
days_left= days_left_for_expiry(expiry_date)
return render(request,'store/dashboard.html',{'days_left':days_left})
{% for i in d %}
<tr>
<td>{{ i.itemname }}</td>
<td>{{ i.itemexpdate }}</td>
<td><b>{{days_left}}</b></td>
</tr>
{% endfor %}
output:
image attached
[enter image description here][1]
[1]: https://i.stack.imgur.com/CU1UZ.png
Just create a
propertyon the Product model:And you can access it from inside the template:
NB you would also need to pass the
Productqueryset to the template through the context: