Subtract 2 integers in Django patterns

Does anyone know how to perform math functions in a Django template? I want to subtract one number from another.

{% for person in persons %} <tr> <td>{{ person.birthday|date:"jS M" }}</td> <td>{{ person.name }}</td> <td>Minus this {% now "Y" %} from this {{ person.birthday|date:"Y" }}</td> <td>{{ person.address }}</td> </tr> {% endfor %} </table> 

Thanks!

+4
source share
2 answers

Do not try to do this in a template. Define a method in your Person model or write a custom template filter.

+2
source

I think the timesince filter can do what is needed.

 {% with now as today %} {{ person.birthday|timesince:today }} {% endwith %} 

However, you should simply consider calculating the value as a method in your Person model. Django's template language is weak for these reasons, for some reason (good, IMHO). Maintaining such logic on your model or computing in your view and passing it as a context variable is almost always the best idea.

Finally, you can always use documents to accomplish a fairly simple task of creating your own tag or template filter, if what you really want to do is to manipulate integers. Again, it often happens that simply passing data through a context or to your object is the best course of action.

+1
source

All Articles