Home > other >  Django - Comparing datetime values in template
Django - Comparing datetime values in template

Time:11-22

I need to display datetime values differently for events in a Django HTML template if the date components are equal, for example, where start and end times occur on the same date, I need to display in this format 'Wed 15 Dec 2021 18:00 to 21:00' and where start and end times occur on different dates, I need to display the full datetime value for both the start and end dates in this format 'Wed 15 Dec 2021 09:00 to Thu 16 Dec 2021 18:00'

I've had a play with the following code but I always get a difference as I don't think it is comparing the formatted date, but the full datetime value.

<li>
    {% if "{{ date.start|date:'D d M Y' }}" == "{{ date.end|date:'D d M Y' }}" %}
        {{ date.start|date:"D d M Y" }} {{ date.start|time:"H:i" }} to {{ date.end|time:"H:i" }}
    {% else %}
        {{ date.start|date:"D d M Y" }} {{ date.start|time:"H:i" }} to {{ date.end|date:"D d M Y" }} {{ date.end|time:"H:i" }}
    {% endif %}
</li>

I could put a boolean flag in the database and do it in the view but would much prefer to do it in the template if possible; any ideas appreciated!

Cheers,

Simon

CodePudding user response:

You shouldn't have nested braces around variables in an if tag, wether they have a filter or not

{% if date.start|date:'D d M Y' == date.end|date:'D d M Y' %}
  • Related