Search code examples
djangodatetimedjango-admindatediff

Django Diff between Dates


I have a project in django and i am trying to render html to pdf. I'm trying to build a table, and i have two varaibles date1 and date2 and i need to do a Diff between date1 and date2.

If the result is more than 20 woriking days show 1 if not show 0

MY HTML

                 {% for item in obj %}
                    <tr> 
                        <td>
                            {% if item.date1 - item.date2 > 20 %}
                            1
                            {% else %}
                            0
                            {% endif %}
                        </td>
                    </tr>
                {% endfor %} 

Solution

  • You can add a method in the model to calculate difference, then use it in the templates/pdf. For example:

    class SomeView(models.Model):
        # .. fields
    
         def date_diff(self):
             diff = self.date1 - self.date2  # returns time delta object
             return abs(diff.days)
    

    And use it in template:

    {% for item in obj %}
        <tr> 
            <td>
                {% if item.date_diff > 20 %}
                  1
                {% else %}
                  0
                {% endif %}
            </td>
        </tr>
    {% endfor %}