views:

47

answers:

2

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_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?

A: 

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.

ars
+1  A: 

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.

Ned Batchelder
Well, they are a `DateField` in the model, which I thought would coerce them into `datetime.date` objects. Am I wrong?
W_P
Disregard the last, got it...
W_P