Format date with Jinja2 and python - 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')}}

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?

django use timedelta in template

I am new django. I have the following code to get the current time and my filter is to convert the string date to dateformat and convert it to solar calendar. Is there any way to find the date of tomorrow in the template and not in any python file?
{% now 'Y-m-d' as value %}
<script>
var today = "{{ value|dateCustomFilter }}";
// var tomorrow = ?
</script>
There is no such filter in Django by default. You could define a custom filter to add an arbitrary days to a date like builtin add filter add to integers.
like:
var today = "{{ value|addDays:1|dateCustomFilter }}"
You could also define a custom template tag or pass it via normal template variables.

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!
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"}}

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