Home > Back-end >  Specifying the display of a django DateField from the model, and not form/input/settings?
Specifying the display of a django DateField from the model, and not form/input/settings?

Time:10-22

I have a Django model with a DateField, like so:

production_date = models.DateField(null=True, blank=True)

I am trying to have that field display as the default Python date format in templates, which looks like "2000-01-01". But in a Django template it displays as "Jan. 1, 2000."

In a Python shell, the date displays properly:

In [4]: resource.production_date                                                              
Out[4]: datetime.date(2014, 4, 20)

In [5]: str(resource.production_date)                                                         
Out[5]: '2014-04-20'

But in the template, when I call production_date, I get the other format.

I have many templates that use this value, and many ways the data gets added to the database. So I do not want to go to each template and change the display. I do not want to change the input form because that is not the only way data gets added. I do not want to change my site settings. I just want the field to display the default Python value. How do I accomplish this? Thank you!

CodePudding user response:

You can apply date filter in template

Example:

{{ birthday|date:"m, d, Y" }}

Django date format reference

CodePudding user response:

I'd make a model method get_production_date.. So I'm not doing a crap ton of template tags, not a fan of them.. and then CTRL Shift F (only HTML files) find production_date and change them to get_production_date

models.py

class MyModel(models.Model):
    production_date = models.DateField('Creation Time')
    # ..other fields

    def get_production_date(self)
        from datetime import datetime # idk if this is required, I assume so?
        return self.production_date.strftime("%Y-%m-%d")

Template usage

{{ MyModelObj.get_production_date }}
  • Related