Don't do that. The Django template system is not the place to put such a logic. Read the Philosophy comments about templates in the Django official website:
If you have a background in programming, or if you’re used to languages which mix programming code directly into HTML, you’ll want to bear in mind that the Django template system is not simply Python embedded into HTML. This is by design: the template system is meant to express presentation, not program logic.
I think the Timmy's comment is right, put the entire logic in a custom filter.