3đź‘Ť
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
2đź‘Ť
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…
2đź‘Ť
Because I like Django built-in filters
timesince
Formats a date as the time since that date (e.g., “4 days, 6 hours”).
Takes an optional argument that is a variable containing the date to
use as the comparison point (without the argument, the comparison
point is now). For example, if blog_date is a date instance
representing midnight on 1 June 2006, and comment_date is a date
instance for 08:00 on 1 June 2006, then the following would return “8
hours”:
{{ blog_date|timesince:comment_date }}
Comparing offset-naive and offset-aware datetimes will return an empty
string.Minutes is the smallest unit used, and “0 minutes” will be returned
for any date that is in the future relative to the comparison point.
- [Django]-Using `defer` or `only` on ForeignKey
- [Django]-Django migrations : relation already exists
- [Django]-Boto3 deprecation warning on import
- [Django]-Is there a framework like now.js for Django?