leongwq
leongwq

Reputation: 191

Django template date comparison

I'm trying to compare dates in my html template. If the current date falls between the start and end date, it will display available. However, my current code only shows Not available even when my date falls between the start and end date.

The now variable is generated by dateTime.now() and is passed to the html. The dates are in the format April 16, 2018, 1:44 p.m. using Django's DateTimeField

<tbody>
    {% for key in keys%}
    <tr>
        <th scope="row">{{key.name}}</th>
        <td>{{key.lock}}</td>
        <td>{{key.start_date}}</td>
        <td>{{key.end_date}}</td>
        {% if now >= key.start_date and now <= key.end_date %}
        <td>Available</td>
        {% else %}
        <td>Not Available</td>
        {% endif %}
        <td><button type="button" class="btn btn-primary btn-rounded btn-sm my-0">Unlock</button></td>
    </tr>
    {% endfor %}
</tbody>

Code from views.py

    keys = Key.objects.filter(user=request.user)
    dateTimeNow = datetime.now()
    args = {'keys': keys, 'now': dateTimeNow}
    return render(request, self.template_name, args)

Upvotes: 0

Views: 1659

Answers (1)

Vincent
Vincent

Reputation: 1564

Add the following method to your Key model:

@property
def is_now(self):
    """
    Returns whether the key is active now
    :return:
    """
    return self.start_date < timezone.now() < self.end_date

Now in your template:

 {% for key in keys%}
    {% if key.is_now %} 
        available
    {% endif %}
 {% endfor %}

Upvotes: 1

Related Questions