1

Here my models.py

class HolidayListView(ListView):
    context_object_name = 'national_holidays'
    model = models.NationalHoliday

I have a template like holiday_list.html

<td>{{ holiday.date_from }}</td>
<td>{{ holiday.date_to }}</td>
<td>{{ holiday.date_to - holiday.date_from }}</td>

how to make <td>{{ holiday.date_to - holiday.date_from }}</td> work, should i do with HolidayListView?...

or

can directly on my templates?...

thank you!

Dicky Raambo
  • 531
  • 2
  • 14
  • 28

3 Answers3

2

You can use custom template filter, but in general Django recommends doing such calculations in the view or model layer, in fact that's why Django templates provide less flexibility in terms of allowed operations.

That's how you could implement it:

Model:

class NationalHoliday(models.Model):
    # Model attributes...

    @property
    def length_days(self):
        return (self.date_to - self.date_from).days

Template:

<td>{{ holiday.date_from }}</td>
<td>{{ holiday.date_to }}</td>
<td>{{ holiday.length_days }}</td>

Related question: How to do math in a Django template?

Maxim Kukhtenkov
  • 734
  • 1
  • 7
  • 20
  • look simple, if i do 2 or more `property` do i need put `@property` each function? – Dicky Raambo May 06 '18 at 01:45
  • Yes, you need to add property decorator to each method that you want to define as class property: http://stackabuse.com/python-properties/. But here property decorator is optional, you can define it as a regular method as well - templating engine will treat both the same. – Maxim Kukhtenkov May 06 '18 at 01:49
1

you can do it with Custom template tags and filters

from django import template
register = template.Library()

@register.filter
def substract_date(date_to,date_from):
    return (date_to - date_from).days

the html will be

<td>{{ holiday.date_to|substract_date:holiday.date_from }}</td>
Lemayzeur
  • 8,297
  • 3
  • 23
  • 50
0

at the template level you can use mathfilters

very useful for me. you can then do the ff:

<td>{{ holiday.date_to|sub:holiday.date_from }}</td>

It is not ideal as @maxim pointed out..the best way is still to do it at the views or models.. but it worked really well for my need.