Search code examples
pythondjangodatetimestrftime

django datetimefield: __str__ give different time from admin display


i am trying to setup the str() to display a datetimefield in admin site. but it give me a different time in different pages. the code is like:

class Order(models.Model):
    order_date = models.DateTimeField(auto_now_add = True,null=True)
    def __str__(self):
        return self.product.name + \
        " ordered on " + \
        str(self.order_date.strftime("%Y%m%d-%H:%M:%S"));

it give a time like 20171027-22:28:40 in the list of My_model. However, "Oct. 27, 2017, 3:28 p.m." is displayed if i click into the entry as the pictures.
enter image description here
enter image description here


Solution

  • the method you overwrite __str__ is for an entire record, instead of displaying for example 'Order: id' the representation you have define which will be fetching.

    So, the first solution is, you can type this in setting.py file

    from django.conf.locale.en import formats as en_formats
    from django.conf.locale.fr import formats as fr_formats
    #....
    
    en_formats.DATETIME_FORMAT = "%Y-%m-%d-%H:%M:%S" 
    fr_formats.DATETIME_FORMAT = "%Y-%m-%d-%H:%M:%S"