0

Good morning. What I would like to achive is that when user posted sooner than 24h from now, I would like to have for example: Posted: 4h ago, but when it's more than 24h, it would be nice to have: Posted: November 10.

First approach is doable by using: {{ post.date_posted|date:"F d, Y" }}, second one: {{ post.date_posted|timesince }}, but is there a way to "mix" them? Is is possible in Django?

northenofca
  • 99
  • 1
  • 8

2 Answers2

1

You can use template tags, by defining a new function formatted_date_text

{{ post.date_posted|date:"F d, Y"|formatted_date_text }}


def formatted_date_text(value):
    # define your funtion
Dharman
  • 30,962
  • 25
  • 85
  • 135
Mukul Kumar
  • 2,033
  • 1
  • 7
  • 14
1

I wrote my own time_utils.py in an app called custom_utils like below based on stack overflow posts. You can modify it accordingly.

import datetime
from django.utils import timezone

def prettydate(d):
    if d is not None:
        diff = timezone.now() - d
        s = diff.seconds
        if diff.days > 30 or diff.days < 0:
            return d.strftime('Y-m-d H:i')
        elif diff.days == 1:
            return 'One day ago'
        elif diff.days > 1:
            return '{} days ago'.format(diff.days)
        elif s <= 1:
            return 'just now'
        elif s < 60:
            return '{} seconds ago'.format(s)
        elif s < 120:
            return 'one minute ago'
        elif s < 3600:
            return '{} minutes ago'.format(round(s/60))
        elif s < 7200:
            return 'one hour ago'
        else:
            return '{} hours ago'.format(round(s/3600))
    else:
        return None

then in the app models, I do:

from custom_utils.time_utils import prettydate

class ForumPost(models.Model):
# your other fields
    published_date = models.DateTimeField(blank=True, null=True)
# your other fields

    def pretty_published_date(self):
        return prettydate(self.published_date)

reference: #Natural/Relative days in Python Jose Segall's answer

EDIT: I faced a problem when querying a dataset using annotate, I was not able to use attributes such as the pretty_published_date. I had to use custom template tags. The following is how to implement prettydate function to custom template tags.

  1. Create templatetags folder in one of the app which is in INSTALLED_APPS in settings file of the project. I put mine under forum folder.
  2. Create a blank __init__.py file inside templatetags folder
  3. Create custom_tags.py
  4. Inside custom_tags.py, add the prettydate function
from django import template
import datetime
from django.utils import timezone

register = template.Library()


@register.filter
def prettydate(d):
    if d is not None:
    # the rest of the function

in template file,

{% load custom_tags %}

{{forumpost.max_activity|prettydate}}

Also make sure that you restart the Django development server. If the server does not restart, Django won't register the tags.

ha-neul
  • 3,058
  • 9
  • 24