Date formatting in Django templates
I am trying to use the |date
filter and running into some problems. Here is the code that outputs an unformatted way:
{% for the_date in event.date_set.all %}
<p>{{ the_date }}</p>
{% endfor %}
this outputs
<p>2010-10-31</p>
<p>2010-12-01</p>
...etc
When I change the code to
{% for the_date in event.date_开发者_StackOverflow中文版set.all %}
<p>{{ the_date|date:"F j, Y" }}</p>
{% endfor %}
it only outputs:
<p></p>
<p></p>
...etc
I tried changing the initial format of the dates to different things, but then I get a validation error trying to input the dates, and get a
ValidationError: [u'Enter a valid date in YYYY-MM-DD format.']
message. I am really stumped by this, could anyone help?
I'll guess that your dates aren't really dates, but are strings with formatted dates in them. The |date filter expects a datetime object, not a string.
That's strange; the following works fine from the interpreter.
In [18]: from datetime import datetime
In [19]: from django.template import Template, Context
In [20]: t = Template('date is {{ thedate|date:"F j, Y" }}')
In [21]: t.render(Context({'thedate': datetime.today()}))
Out[21]: u'date is September 7, 2010'
It might be worth trying the above at your end to try and isolate the problem. If it doesn't work, then maybe you need to need to update the django version or something (not likely, I admit).
Another thing is to make sure you don't have a typo somewhere. For examples, if your for loop is just returning NULLs or empty strings, this could be the cause. As a sanity check, try:
{% for the_date in event.date_set.all %}
<p>{{ the_date }}</p>
<p>{{ the_date|date:"F j, Y" }}</p>
{% endfor %}
If the problem is consistent, it should be reflected in the output.
Its a bug in SQLlite. refer https://code.djangoproject.com/ticket/11851
精彩评论