Specifying the display of a django DateField from the model, and not form/input/settings?

485 Views Asked by At

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?

2

There are 2 best solutions below

2
Nealium On BEST ANSWER

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 }}

Edit

I'm not 100% on what accessor are, but it sounds very class basey, which I don't use.
I doubt you can use a model method directly like that

But! for my admins, I use custom columns in my admin table like:

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('name', 'calculated_total',)

    def calculated_total(self, obj):
        return obj.get_calculated_total()

..so like, there's gotta be something similar in class based views, right??
I've been googling, but I cannot find the correct words to describe it..

2
Hashem On

You can apply date filter in template

Example:

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

Django date format reference