Django Template Engine datetime comparison not working

48 views Asked by At

I'm trying to build a small BBS-like app in Django, and I want to be able to restrict users from deleting posts more than 30 minutes old. However, I can't get the datetime comparison to work in the template engine.

Here is a snippet of my views:

context = {
            ...
            "message_time" : datetime.utcnow() + relativedelta(minutes=-30) 
        }

And here is the django template in the html:

{% if request.session.userid == post.user.id and post.created_at >= message_time %}
            <form action="/wall/message/{{ post.id }}/delete" method="POST">
            {% csrf_token %}
            <button type="submit">Delete</button>
            </form>
            {% endif %}

For some reason, the delete button doesn't appear with this snippet, however it works without it (i.e. the message id/session id functionality is fine). I've tried using different combos of relativedelta +/- 30 minutes, created_at greater/less than message_time, but nothing seems to work.

1

There are 1 answers

0
ryan.marean On

For anyone reading this, I figured out the issue:

datetime.utcnow() is timezone naive (despite the name). Therefore, at some point when the template was rendering, the message time "reset" to midnight UTC (I can't fully explain why, but this answer is what clued me in).

Using datetime.now(timezone.utc) allowed me to pass the datetime as aware and UTC, which stopped the issue from happening.