0

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 %} 
Pedro Mariz
  • 151
  • 2
  • 20

2 Answers2

2

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 %} 
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • you need to make sure date1 is bigger than date2. Also days does not count working days, Maybe this answer will help: https://stackoverflow.com/a/3615984/2696165 – ruddra Mar 21 '19 at 13:05
  • I have updated the answer with `abs` to get positive value regardless which date is bigger. – ruddra Mar 21 '19 at 13:29
  • yeh it's working , but to do only working days , how can i do? – Pedro Mariz Mar 22 '19 at 09:13
  • You can use this library: https://github.com/ogt/workdays or please use any answer which suits you( shared with my previous comment) :) – ruddra Mar 22 '19 at 10:20
1

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 %}
Aarif
  • 1,595
  • 3
  • 17
  • 29