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

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!

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).

If {{ facets.dates.created.start }} is a datetime object then you can use
{{ facets.dates.created.start|date:"SHORT_DATE_FORMAT" }}
In case you are providing a string you can create a template filter to convert the string to datetime object and apply the date filter
#register.filter
def stringformat(value, args):
return datetime.strptime(value, args)
In the template:
{{ facets.dates.created.start|stringformat:"%Y-%m-%dT%H:%M:%SZ"|date:"SHORT_DATE_FORMAT" }}

You can use Django template tags for this. You need to use {{my_date|date:"some_format"}} which takes "my_date" as the argument (it should be a date object) to "date" tag and then formats it based on the given format.
{{facets.dates.created.start|date:"d/m/Y"}}

Related

Iterate over json string items in jinja2

Hi I need to send data in string format to my jinja templates, and the render them. The only way I found is to format my data as JSON and send it as a string to the renderer. But I don´t know how to use it in the templates, it seems that the tojson filter it´s not for this purpose, because it keeps rendered a string.
to keep it simple I'm doing something similar to:
import json
a = {"a":1,"b":[1,2,3,4]}
response = json.dumps(a)
in template:
{{ response }}
{{ response|tojson }}
both give a string response, not a dict or an object that I can use to render based on the values
You can import json to use it's load function to load it into jinja.
from json import loads
environment = jinja2.Environment(whatever)
environment.filters['load'] = loads
{{ response|load }}
Reference:
Import a Python module into a Jinja template?

Comparing dates using a comparator inside Django template

I am trying to compare the end date of an event with today's date to see if the event has ended. If the event has ended, the website user would not have a button to enrol and if the event has not started or is ongoing, the user would have a button to enrol in html.
I have tried this in my html template:
{% if event.end_date|date:"jS F Y H:i" <= today|date:"jS F Y H:i" %}
{% include 'event/includes/enroll.html' %}
But the button shows whether or not the event has ended already.
I wanted to add a method in my django model like this:
#property
def is_today(self):
return self.datefinish == datetime.today().date()
But I am not sure how to import the method and use it in html template then.
I wanted to try to add a variable in my view like this: (Django - Checking datetime in an 'if' statement)
is_today = model.end_date >= datetime.today()
return render_to_response('template.html', {'is_today': is_today})
But a colleague has written a Class-based view to render the template and not sure how to add the variable to render using the class-based view. I also got an error:
TypeError: '>=' not supported between instances of 'DeferredAttribute' and 'datetime.datetime'
If anyone can advice on how to best achieve what I need, I would be grateful :D
Hello why dont you use a custom_filter, that will return True or False in your template ? (https://docs.djangoproject.com/fr/3.1/howto/custom-template-tags/):
import datetime
from django import template
from django.conf import settings
register = template.Library()
#register.filter
def event_ended(date_event):
return date_event >= datetime.date.today()
{% load poll_extras %}
{% if event.end_date | event_ended %}
{% include 'event/includes/enroll.html' %}
The link from the documentation told you where to put the custom template

Format date with Jinja2 and python

i need to format this date on the template because comes from the database on a dictionary.
I got this date displayed on my template:
1996-08-22
And i want to be like this:
22-08-1996
here is my code for it :
{{date['Fundação'] }}
I try to use with strftime but i got an error:
{{date['Fundação']|strftime('%d-%m-%Y')}}
The error:
jinja2.exceptions.TemplateAssertionError: no filter named 'strftime'
You can implement a python function that will handle the date.
You can consume it from your template.
Example:
def reverse_date(a_date):
d = a_date.split('-')
d.reverse()
reverse_d = '-'.join(d)
return reverse_d
template = Template('your template')
template.globals['reverse_date'] = reverse_date
# now you can use it in your template
{{ reverse_date(date['Fundação']) }}
You can treat variables in a jinja2 template as Python ones. To change the date format use the datetime build-in method, not a filter:
{{date['Fundação'].strftime('%d-%m-%Y')}}

How to change DateField format representation

i do have a field in model DateField
so when i render it on webpage it shows
12-30-2012
and i need
30.12.2012
i tried to use inside template
{{ item.pub_date.strftime("%d.%m.%Y") }}
but i recieve and error of parsing. in console it works fine.
then i tried to make a new method in model
get_pub_date(self):
self.pub_date.strftime("%d.%m.%Y")
and i recieve same error parsing of template when i call this method in tempalte
Use date template filter:
{{ item.pub_date|date:"d.m.Y" }}
Also note:
When used without a format string:
{{ value|date }}
...the formatting string defined in the DATE_FORMAT setting will be used, without applying any localization.

Django date filter: how come the format used is different from the one in datetime library?

For formatting a date using date filter you must use the following format :
{{ my_date|date:"Y-m-d" }}
If you use strftime from the standard datetime, you have to use the following :
my_date.strftime("%Y-%m-%d")
So my question is ... isn't it ugly (I guess it is because of the % that is used also for tags, and therefore is escaped or something) ?
But that's not the main question ... I would like to use the same DATE_FORMAT parametrized in settings.py all over the project, but it therefore seems that I cannot ! Is there a work around (for example a filter that removes the % after the date has been formatted like {{ my_date|date|dream_filter }}, because if I just use DATE_FORMAT = "%Y-%m-%d" I got something like %2001-%6-%12)?
use DATE_INPUT_FORMATS.
from django.conf import settings
py_format = settings.DATE_INPUT_FORMATS[0]
While this may not be the "right" answer, I got around this by adding another variable to settings and using it all over the place. I have dates formatted in JavaScript, datetime, and Django templates, so I added all three.
TIME_ZONE = 'America/Phoenix'
DATETIME_FORMAT = 'm-d-Y H:m:s T'
DATE_FORMAT = _('m-d-Y')
JS_DATE_FORMAT = _('mm-dd-yy')
PERC_DATE_FORMAT = _('%m-%d-%Y')
I also run them through localization for our customers in Mexico who prefer a different format.
Not part of your main question but could be handy anyway. I found it mentioned in the docs that the date filter format is based on php's date format.
You could try writing a custom filter:
#app/templatetags/python_date.py
from datetime import date, datetime
from django import template
register = template.Library()
#register.filter(name='pythondate')
def python_date_filter(value, arg):
if not type(value) == date and not type(value) == datetime:
raise Exception('Value passed in to the filter must be a date or a datetime.')
return value.strftime(str(arg))
usage in templates:
{% load python_date %}
{{ some_date|pythondate:'%Y-%m-%d' }}

Categories

Resources