Search code examples
djangodjango-templatesdjango-template-filters

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?


Solution

  • 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 %}