Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display human time (x days ago, or now) in django admin?

Tags:

How can I display time/date format used in facebook/twitter in django admin?

from django.db import models
from datetime import datetime


class Course(models.Model):

      date = models.DateTimeField(auto_now_add=True)
      title = models.CharField(max_length=255)
      description = models.TextField()

      def get_date(self):
          time = datetime.now()
          if self.date.day == time.day:
              return str(time.hour - self.date.hour) + " hours ago"
          else:
              if self.month == time.month:
                   return str(time.day - self.date.day) + " days ago"

          return self.date

      def __str__(self):
          return self.title

Admin.py

  from django.contrib import admin
  from .models import Course   

  @admin.register(Course)
  class CourseAdmin(admin.ModelAdmin):
      list_display = ('title', 'description', 'get_date',)

Tried a number of combination to import date/time but still get errors as shown in the image. enter image description here

If I use the get_date: I get the following error:

AttributeError at /admin/courses/course/
'Course' object has no attribute 'month'
Request Method: GET
Request URL:    http://localhost:8000/admin/courses/course/
Django Version: 1.10.5
Exception Type: AttributeError
Exception Value:    
'Course' object has no attribute 'month'
Exception Location: /courses/models.py in get_date, line 17

Expected result to display the created_at and updated_at in human time. To show

  • 2 days ago
  • Now
  • A few minutes ago

Expected result: 2 days ago, or 3 hours ago. or better yet, a few hours ago.

enter image description here