7👍
You can use extra methods in your model like this:
class Example(models.Model):
date = models.DateTimeField(auto_now_add=True)
def get_date(self):
time = datetime.now()
if self.created_at.day == time.day:
return str(time.hour - self.created_at.hour) + " hours ago"
else:
if self.created_at.month == time.month:
return str(time.day - self.created_at.day) + " days ago"
else:
if self.created_at.year == time.year:
return str(time.month - self.created_at.month) + " months ago"
return self.created_at
or you can create some utils functions for do that and just use it in your model method if you want to use in more situations
Here is the documentation for Django admin, here you find all that you need:
https://docs.djangoproject.com/en/1.10/ref/contrib/admin/
45👍
There is an accepted answer however I want to suggest another thing who came here for a solution which can be used in templates.
Django has a contrib package called django.contrib.humanize
. Add this to your INSTALLED_APPS, then use {% load humanize %}
in your template, after that, you can use value|naturaltime
template tag. “value” will be your date.
Let’s say content.created
, which contains the creation date of your content. It’s a datetimefield object. So, you can use this: content.created|naturaltime
. It’ll convert the date e.g from July 14, 2018 11:30 to “3 days 1 hour ago”.
- Tracking changes to all models in Django
- SQL injection hacks and django
- Set db per model in django
- Adding forgot-password feature to Django admin site
- How to populate user profile with django-allauth provider information?
17👍
Turns out the template filters can be accessed directly from your Python codebase. Something like this:
from django.contrib.humanize.templatetags import humanize
class Example(models.Model):
date = models.DateTimeField(auto_now_add=True)
def get_date(self):
return humanize.naturaltime(self.date)
The get_date()
function can also be located within your CourseAdmin
class.
- How to point correctly to static image in django
- Django CSRF cookie not set correctly
- Save the related objects before the actual object being edited on django admin
- Django Tables – Column Filtering
4👍
I found this useful
use it in your template, eg. index.html
{{ post.timestamp | timesince }}
- Django Rest Framework 3.1 breaks pagination.PaginationSerializer
- Django: How to automatically change a field's value at the time mentioned in the same object?
- Overriding Size of Django Admin Multi-select Widget
- No fixture named 'X' found
- Django OneToOneField with possible blank field