Django ifequalnaturalday
我不知道为什么,但这个条件对我来说永远不会评估为真。我在 urls 文件中输入 datetime.today() 。我错过了什么吗?
模板:
{% load humanize %}
{{ entry.date|naturalday }} {# Evals to "today" #}
{% ifequal entry.date|naturalday "today" %}
True
{{ entry.date|date:"fA"|lower }} {{ entry.date|naturalday|title }}
{% else %}
False
{{ entry.date|naturalday|title }}
{% endifequal %}
I'm not sure why, but this condition will never evaluate True for me. I'm feeding it datetime.today() in the urls file. Am I missing something?
Template:
{% load humanize %}
{{ entry.date|naturalday }} {# Evals to "today" #}
{% ifequal entry.date|naturalday "today" %}
True
{{ entry.date|date:"fA"|lower }} {{ entry.date|naturalday|title }}
{% else %}
False
{{ entry.date|naturalday|title }}
{% endifequal %}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我刚刚在 Django 1.1.1 下测试了它,它对我来说工作得很好。
您运行的是哪个版本的 Django?
但是,还有一些其他问题可能会给您带来问题:
我还注意到,在您的问题中,您有
{% load humaize %}
,其中包含拼写错误(应为{% load humanize %}
)。我不确定这是否在您的真实代码中或只是在您的问题中。如果您确实在
urls.py
中使用datetime.today()
,正如您所说,请注意这可能会导致问题,因为该值是仅在首次创建extra_context
字典时计算一次(因为“today”的值仅计算一次)。这可能意味着代码将在应用程序运行的第一天运行,然后在第二天失败。您可能不会注意到这一点,直到您部署到应用程序整夜运行而无需重新启动的环境中。如果您希望它确实是“今天”,只需传入函数
datetime.today
而不是datetime.today()
即可。这样模板就会在每次渲染时调用它。I just tested this under Django 1.1.1 and it works just fine for me.
Which version of Django are you running?
However, there are a few other issues that could be causing you problems:
I also noticed that in your question you have
{% load humaize %}
, which contains a typo (should be{% load humanize %}
). I'm not sure if this is in your real code or just in your question though.If you are really using
datetime.today()
in yoururls.py
, as you say, please be aware that this could cause problems, since the value is only going to be calculated once, when theextra_context
dictionary is first created (since the value of "today" will only ever be calculated once). This could mean the code will work on the first day the app is running, then fail the second day. You likely wouldn't notice this until you deploy to an environment where the app runs overnight without being restarted.If you want it to really be "today", just pass in the function
datetime.today
rather thandatetime.today()
. That way the template will call it on each render.