django use timedelta in template - python

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.

Related

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 display current year in Flask template?

I am looking to find out how to output the current year in a Flask template. I know in Django you can use {% now "Y" %}., but is there a Flask equivalent? I have been unable to find anything during my research thus far.
Use a template context processor to pass the current date to every template, then render its year attribute.
from datetime import datetime
#app.context_processor
def inject_now():
return {'now': datetime.utcnow()}
{{ now.year }}
Or pass the object with render if you don't need it in most templates.
return render_template('show.html', now=datetime.utcnow())
For moment there is Flask Moment. It is powerful like Moment, and easy to use in Flask. To display the year in the user's local time from your Jinja template:
<p>The current year is: {{ moment().format('YYYY') }}.</p>
If using Jinja2 is too cumbersome and you are using Jinja2 in a context of a browser that you can simply use Javascript.
Using Simple Javascript
<span id="year"></span>
const year = document.querySelector('#year');
if (year) {
year.innerHTML = new Date().getFullYear().toString();
}
JavaScript library like moment.js
<script>
document.write(moment("2012-12-31T23:55:13 Z").format('LLLL'));
</script>

Parse JSON object to Django template

I am trying to parse a JSON object to Django template so that I can parse this json object to javascript.
Here how my view creates and parse the json object to the template:
countries = Country.objects.filter(Enabled=True)
citiesByCountry = {}
for country in countries:
citiesInCountry = City.objects.filter(Enabled=True, Country=country)
cities = []
for city in citiesInCountry:
cities.append(city.Name)
citiesByCountry[country.Name] = cities
context = {'citiesByCountry': json.dumps(citiesByCountry)}
return render(request, 'index.html', context)
Now I would like to retrieve all the keys (which will be countries) to my template this way:
{% for country in citiesByCountry%}
<option>{{ country }}</option>
{% endfor %}
But what I get is an option for each character in strings instead of the country name as a whole.
I tried to use .item1 but this didn't work either.
I don't show JavaScript code in my example above as the intent of the question is how to parse and retrieve strings from a JSON object. I need to process this data using javascript later. In specific once the user change country I would like to populate another dropdown that will handle the cities, and therefore I thought to use JSON and Javascript to achieve that, as I don't want to refresh the page on each change.
Any help?
To answer you question in the title:
In <head> (or somewhere), build your array of counties:
<script>
var country_objs = [];
{% for country in citiesByCountry%}
country_objs.push({{country|escapejs}});
{% endfor %}
<\script>
Docs for the filter: https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#escapejs
Then you can use it in JavaScript (but not in Django template). For example:
<select id="cities"><\select>
<script>
var $cities_select = $("#cities");
$(country_objs).each(function(){
$cities_select.append('<option value="' + this.id_or_something + '">' + this.name + '<\option>');
});
<\script>
But from your example I don't see why you need to encode it in JSON in the first place. Why not just pass a dict into the template (via context, just as everything else)?
P.S.
Sorry for using jQuery, l'm just lazy :)
I think you have two options:
Parse the JSON in the <option> tags with javascript.
<script>
var json = JSON.parse({{citiesByCountry}});
//Loop through json and append to <option>
</script>
Add an extra context that isn't JSON serialized. This is a little redundant but a bit simpler.
context = {'citiesByCountry_json': json.dumps(citiesByCountry), 'citiesByCountry': citiesbyCountry}
To be honest, I'd go for the second option since I don't see why you need to send it to the template in JSON in the first place.
When you do citiesByCountry = json.dumps({'a': "b", 'c': None}), citiesByCountry is a string. This is why you get character after character when you iterate over it.
This string representing a JSON object, you can "affect" as-is to a JavaScript variable:
var citiesByCountry = {{ citiesByCountry }};
Which will output something like:
var citiesByCountry = {"a": "c", "d": null};
However, considering what you want to achieve:
In specific once the user change country I would like to populate another dropdown that will handle the cities
I highly recommend you to checkout django-autocomplete-light, which in addition to providing auto-completion, provides a way to filter results based on other fields. This will save you much efforts.

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

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