2

I'm rather new to Class Based Views, so this is probably obvious, but any tips are appreciated. I want to display "time left" for each item on a list. That is if I have 10 objects, each should display in the template the number of days, hours, mn left until a deadline arrives. Here's my attempt:

model.py

class Law(models.Model):
    deadline = models.DateTimeField(_(u'The Deadline'),)
    name = ..
    more_stuff = ..

views.py

class LawList(ListView):
    model = Law
    context_object_name = 'law'
    template_name = 'template.html'

template.html

{% for l in law %}
   <h3>{{ l.deadline }} - {{l.name }} </h3>
     {{l.more_stuff}}
{% endfor %}

all good up to here. However I would like to have {{l.time-left}} instead of {{l.deadline}}. Is there a way for the view to calculate this and pass it to the template?

I thought of adding a get_context_data to the 'LawList' view, but I don't know how to do so for every item in my list. Below is what works for a single item.

# views.py, below the section above
def get_context_data(self, **kwargs):
     context = super(LawList, self).get_context_data(**kwargs)
     context['time_left'] = Law.objects.all()[0].deadline - timezone.now() 

but I'm a little stuck. Thanks!

Massagran
  • 1,781
  • 1
  • 20
  • 29

1 Answers1

2

have a look at the timeuntil template tag

second
  • 28,029
  • 7
  • 75
  • 76
  • Never seen that one before, love discovering these little gems – Josh Smeaton Dec 10 '12 at 09:40
  • thanks. that was easy :). I've also found it was a duplicate. see [here](http://stackoverflow.com/questions/7887897/calculate-number-of-days-between-two-dates-inside-django-templates) and a little more detail [here](http://stackoverflow.com/questions/6494921/how-to-display-x-days-ago-type-time-using-humanize-in-django-template) – Massagran Dec 10 '12 at 10:08