I know I can get the current date as a str
in a Django template (using the template tag now
), like this:
{% now "Y-m-d" as today_str %}
<p>{{ today_str }}</p>
But I cannot use that for comparissons:
{% now "Y-m-d" as today_str %}
{% for elem in object_list %}
{% if elem.date < today_str %} {# WRONG: this compares 'date' and 'str' #}
<p>{{ elem.pk }} before today</p>
{# do some other rendering #}
{% endif %}
{% endfor %}
Possible solutions:
I know I can pass a context variable to the template, but it requires code in my view:
# in my class-based-view in 'views.py'
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx['today'] = timezone.now()
return ctx
Or I can create a custom template tag, but that is even more additional code.
As you can see I have workarounds for my problem, but I would like to know if there is a buit-in way to get the current date
(or datetime
) in the template?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…