Django templatetags ISO到目前为止 [英] Django templatetags ISO to date
问题描述
这个问题类似于这一个,但在我看来是截然不同的。 p>
我有一个具有一些datetime属性的对象。为了序列化并存储为JSON字符串,我调用 .isoformat
方法(使用自定义JSON编码器)。
相反,我预计Django模板标签能够为我解决这个问题。我有一个JSON对象,通过调用 json.loads
转换为字典。结果属性的值为$ code> 2015-10-07T14:57:00.501597 + 00:00 当我简单地称之为 {{my_object.date} }
。但是,当我将它传递给 date
模板标签时,根本就不会输出任何输出。我正在尝试 {{my_object.date | date}}
,但也可以像 {{my_object.date |日期:'Y-m-d'}}
。
日期是否无法转换这些值?我清楚地记得在某些时候这样做,但不确定具体细节。
有没有办法正确调试?现在我只是没有看到任何输出,也没有任何东西出现在日志中。
为什么不将它转换为将datetime实例传递给模板?然后,您可以使用模板中的 date 过滤器来输出任何你想要的。如果你不/不能这样做,你必须编写一个自定义过滤器标签来读取isoformat日期并输出你想要的。
使用 dateutil库的示例:
从django导入模板
import dateutil
register = template.Library()
@ register.filter(name = 'to_date')
def to_date(value):
return dateutil.parser.parse(value)
This question is similar to this one but distinctly different, in my opinion.
I have an object that has some datetime attributes. In order to serialize it and store as a JSON string, I call the .isoformat
method (using a custom JSON encoder).
The other way around, I expected Django template tags to be able to resolve this for me. I have a JSON object that I convert to a dictionary by calling json.loads
. The resulting attribute has the value 2015-10-07T14:57:00.501597+00:00
when I simply call it as {{ my_object.date }}
. When I pass it to the date
template tag, however, I get no output at all. I'm trying {{ my_object.date | date }}
but also things like {{ my_object.date | date:'Y-m-d' }}
.
Is date not able to convert these values? I distinctly remember doing this at some point, but am not sure on the specifics..
Is there a way to debug this properly? Right now I'm just not seeing any output, and nothing appears in the logs either.
Why not convert it to a datetime instance before passing it to the template? Then you could use the date filter in the template to output whatever you want. If you don't/can't do that, you'll have to write a custom filter tag to read the isoformat date and output it how you want to.
Example using dateutil library:
from django import template
import dateutil
register = template.Library()
@register.filter(name='to_date')
def to_date(value):
return dateutil.parser.parse(value)
Docs for custom filter tags.
这篇关于Django templatetags ISO到目前为止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!