Search code examples
pythondjangodjango-templatesdjango-haystacksolr4

How to parse "2015-01-01T00:00:00Z" in Django Template?


In my Django html template, I get my SOLR facet_date result using haystack in the format "2015-01-01T00:00:00Z". How can I parse it in format "01/01/2015" in my template? My template is

{{ facets.dates.created.start }}

What "|date:" option should I add to my template? Thanks!


Solution

  • If your date is a ISO string instead of a Python datetime.datetime, I guess you will have to parse it on the view or write a custom filter:

    # yourapp/templatetags/parse_iso.py
    from django.template import Library
    import datetime
    
    register = Library()
    
    @register.filter(expects_localtime=True)
    def parse_iso(value):
        return datetime.datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ")
    

    Then at the template:

    {% load parse_iso %}
    
    {{ value|parse_iso|date:'d/m/Y'}}
    

    [edit]

    got this error Exception Type: TemplateSyntaxError at /search/ Exception Value: 'parse_iso' is not a valid tag library: Template library parse_iso not found

    Make sure you follow the code layout prescribed in the docs:

    yourapp/
        __init__.py
        models.py
        ...
        templatetags/
            __init__.py
            parse_iso.py
        views.py
    

    Your country may use m/d/Y (01/01/2015 is ambiguous, I suggest using an example like 31/01/2015 so it is clear if the first number represents day or month).