Django templatetags ISO to date

╄→尐↘猪︶ㄣ 提交于 2019-12-13 18:39:56

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/33187986/django-templatetags-iso-to-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!