Home > Software design >  How can i print number of days between of each products expiry date and today date in a template //d
How can i print number of days between of each products expiry date and today date in a template //d

Time:12-27

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

CodePudding user response:

Just create a property on the Product model:

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)

    @property
    def days_left(self) -> str:
        today = date.today()
        expiry = self.itemexpdate
        delta = expiry - today
        return str(delta.days)

And you can access it from inside the template:

{% for i in d %}             
    <tr>                    
        <td>{{ i.itemname }}</td>
        <td>{{ i.itemexpdate }}</td>
        <td><b>{{ i.days_left }}</b></td>
    </tr>
{% endfor %}

NB you would also need to pass the Product queryset to the template through the context:

def home(request):
     d = Product.objects.all()
     return render(request,'store/dashboard.html',{'d':d})
  • Related