Very simple filter that returns one of the following by default:
- # days ago
- yesterday
- today
- January 01, 2007
Example template code:
This thread was started {{ post.date_created|dayssince }}.
This thread was started today.
E-mail sent: {{ email.date_sent|dayssince|capfirst }}
E-mail sent: Yesterday
Object created: {{ obj.date_created|dayssince|upper }}
Object created: 12 DAYS AGO
User's bogus birthday: {{ user.get_profile.bday|dayssince }}
User's bogus birthday: April 20, 3030
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | from django import template
import datetime
register = template.Library()
def dayssince(value):
"Returns number of days between today and value."
today = datetime.date.today()
diff = today - value
if diff.days > 1:
return '%s days ago' % diff.days
elif diff.days == 1:
return 'yesterday'
elif diff.days == 0:
return 'today'
else:
# Date is in the future; return formatted date.
return value.strftime("%B %d, %Y")
register.filter('dayssince', dayssince)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Hi,
there is just a 'little' bug, you have an elif without an if before, and an if after elif..
Thanks for this filter :p
#
args['days_since'] = dayssince(profile.date_joined) Error:
unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime'
#
for better way use
from django.utils import timezone
today = timezone.now()
instead
today = datetime.date.today()
#
Please login first before commenting.