简体   繁体   中英

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 %} 

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 %} 

you should perform the calculation in the backend and send number of days value while rendering the template

difference=item.date1-item.date2
days=difference.days

and in template

{% if days > 20 %}
   1
{% else %}
   0
{% endif %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM