Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template counting days from now to specific date

I have a model with DateField:

end_date = models.DateField(default=datetime.date.today)

In the template I need to calculate how many days there is to the end_date from now. I tried:

{% now "d m Y"|timeuntil:placement.end_date|date:"d m Y" %}

but it doesn't work. How can I get number of days until that date?

like image 909
TityBoi Avatar asked Oct 20 '25 16:10

TityBoi


2 Answers

There is a limitation to using Django functionality in Templates. You could solve this by combining the timesince and timuntil methods to calculate the difference between two dates. However you would benefit more from doing this in a python view and then pass the result to the template.

This way you can truly use the power of Datetime. So in your views.py and the specific function that renders the template, include this:

d0 = datetime.now().date()
d1 = placement.end_date
delta = d0 - d1
print delta.days

You can read more about the Datetime documentation here. Now you can pass that variable along in a context, or by itself to be rendered by the template

like image 130
pastaleg Avatar answered Oct 23 '25 05:10

pastaleg


Option 1: Create a custom filter

Create a custom filter function which grabs the current date and calculates the days.

In your template you simply use:

{{ placement.end_date | days_until }}

To define and register the filter, include this code in a python file:

from datetime import datetime
from django import template

register = template.Library()

@register.filter
def days_until(date):
    delta = datetime.date(date) - datetime.now().date()
    return delta.days

More about Django custom template tags and filters here.

Option 2: Calculate the days in your view and store it in the context

This is straightforward for one date. You calculate the days and store the information in the context:

from datetime import datetime
delta = placement.end_date - datetime.now().date()
context['days_left'] = delta.days

In your template you access it directly:

{{ days_left }}

But, if you want to pass a list of "placements" to the template, you will have to "attach" this new information to every placement. This is a different topic and the implementation depends on the project... you can create a wrapper over placement... or store the days_left in a different dictionary...

like image 22
addmoss Avatar answered Oct 23 '25 05:10

addmoss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!