Dicky Raambo
Dicky Raambo

Reputation: 523

Arithmetic Operator on django Templates

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!

Upvotes: 1

Views: 4439

Answers (3)

Richard Rosario
Richard Rosario

Reputation: 81

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.

Upvotes: 0

Maxim Kukhtenkov
Maxim Kukhtenkov

Reputation: 724

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?

Upvotes: 2

Lemayzeur
Lemayzeur

Reputation: 8525

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>

Upvotes: 1

Related Questions