0

I have two dates in a template that I need to compare in an if statement.

Date1 is from the created field of a data element {{ endjob.created|date:"Y-m-d" }} that is displayed as 2016-09-12

Date2 if from an array {{ pay_period.periods.0.0 }} that is displayed as 2016-09-04

Therefore I am trying to ask to display information only if Date1 >= Date2 but I do not get any data.

Can you help me with how to clash dates in templates in Django

This is my code:

<tbody>     
{% for endjob in endjob %}
        {% if endjob.created|date:"Y-m-d" >= pay_period.periods.0.0  %}
            <tr>
            <td><a href="{{ endjob.get_absolute_url }}" title="Goto Form">{{ endjob.event.name }}</a><br /></td>
            <td>{{ endjob.event.job_no}} <br /></td>
            <td>{{ endjob.event.job_type}} <br /></td>
            <td>{{ endjob.code }} <br /></td>
            <td>{{ endjob.crewid }}<br /></td>
            <td>{{ endjob.workers }}<br /></td>
            <td>{{ endjob.created|user_tz:user|date:"M j, Y" }}<br /></td>
            </tr>
       {% endif %}
{% endfor %}

Les Hornery
  • 1
  • 1
  • 4

1 Answers1

0

You are probably comparing two different data types which is why you are not getting anything. By doing endjob.created|date:"Y-m-d",you are converting endjob.created to a string. Yes, {{ pay_period.periods.0.0 }} is displayed as the string '2016-09-04'. That is what the {{ }} thing does. However in the expression endjob.created|date:"Y-m-d" >= pay_period.periods.0.0, you are comparing a string VS the original data type of pay_period.periods.0.0.

To solve this, just make sure the datatypes match upon comparison. You can probably get away with endjob.created|date:"Y-m-d" >= pay_period.periods.0.0|date:"Y-m-d", but I do not recommend it. Unless there is a very good reason you must do it this way, I suggest doing the comparison elsewhere other than on the template level, and then pass a boolean or call a boolean attribute instead like so.

Community
  • 1
  • 1
Wannabe Coder
  • 1,457
  • 12
  • 21