i have a model post which has a created field so i cant print the day created, but it comes out as a full date while all i need is the time since i.e(3 hrs ago, not 21st Month/Year)
class post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
Topic = models.ForeignKey(topic, on_delete=models.CASCADE)
post = models.TextField(max_length=500)
created = models.DateTimeField(auto_now_add=True)
update = models.DateTimeField(auto_now=True)
liked = models.ManyToManyField(User, related_name='likes', default=None, blank=True)
def __str__(self):
return f'{self.post}'
@property
def num_likes(self):
return self.liked.all().count()
my views.py
def index(request):
posts = post.objects.all().order_by('-created')
topics = topic.objects.all()
comment = comments.objects.all()
return render(request, 'base/home.html', {'posts' : posts, 'topics' : topics, 'comments' : comment})
in my template
{% for post in posts %}
<div class="post-body-content">
@{{post.author}} - <small><i>{{post.created}} </i></small> <br>
Topic: <a href="{% url 'topic' post.Topic %}">{{post.Topic}}</a> <br>
<a href="{% url 'post' post.id %}">{{post}}</a> <br>
you can use the timesince template tags as per django docs django documentation
{{post.created|timesince}}
for example
{% for post in posts %}
<div class="post-body-content">
@{{post.author}} - <small><i>{{post.created|timesince}} </i></small> <br>
Topic: <a href="{% url 'topic' post.Topic %}">{{post.Topic}}</a> <br>
<a href="{% url 'post' post.id %}">{{post}}</a> <br>