Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting date in django template

My template renders the tag {{ test.date}} in the following format -

2015-12-15T23:55:33.422679

When I try to format it using django's built in template tag date, it doesn't display anything.

Variations I've tried:

{{ test.date|date:"SHORT_DATE_FORMAT" }}

{{ test.date|date:"D d M Y" }}

models.py:

class Human(models.Model):
    name = models.CharField(max_length=50,default='',blank=False)


class Test(models.Model):
    human = models.ForeignKey(Human)
    date = models.DateTimeField(default=datetime.now)

views.py:

def list(request):
    h = Human.objects.all()
    s=[]
    for her in h: 
        t = h.test_set.all()
        s.extend(t)
    context = RequestContext(request, {'test_list': s,})
    return render_to_response('template.html', context)

I am then using it in template like this:

{% for test in test_list %}
     {{test.date}}
{% endfor %}

What am I missing?

like image 404
qwertp Avatar asked Oct 18 '22 20:10

qwertp


2 Answers

Answering an OLD post... but, the answer doesn't seem (to me) to be answering the original question - which was WHY isn't the Django inline template date formatting working...

The answer is (I believe) that the author was trying to output to his page something like:

"This is my date:{{test.date|date:"D d M Y"}}."

The problem, if this is truly what was being tried, is that the double quotes don't work in this situation. You need to do the following instead:

"This is my date:{{test.date|date:'D d M Y'}}."

Note the single quotes...

like image 146
jaytate Avatar answered Oct 21 '22 16:10

jaytate


I'm not sure what you want from this logic, but I think you can use this:

def list(request):
    test = Test.objects.all()
    return render(request, 'template.html', {'test':test})

and in template:

{% for t in test %}
    {% t.date %}
{% endfor %}

if you want display human, just add in cycle {% t.human.name %}

like image 32
Ivan Semochkin Avatar answered Oct 21 '22 15:10

Ivan Semochkin