7

I have a date field called "birthdate" and property called "lifespan" in a django model.

Field

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

Property

@property
def lifespan(self):
    return '%s - present' % self.birthdate

Currently lifespan returns the date in the "yyyy-mm-dd" format.

How can I changed this date format to "mm/dd/yyyy"?

I know how to do it in a django template with a filter but wanted to see if there was a similar "filter" that I can use in a Django model.

I appreciate the feedback.

Andy
  • 49,085
  • 60
  • 166
  • 233
bbrooke
  • 2,267
  • 10
  • 33
  • 41

2 Answers2

9

For full control, use strftime:

@property
def lifespan(self):
    return '%s - present' % self.birthdate.strftime('%m/%d/%Y')

strftime doesn't have all the formatting options that Django's date filter does, so if you want one of those you could call the filter as a function:

from django.template.defaultfilters import date

@property
def lifespan(self):
    return '%s - present' % date(self.birthdate, "n/j/Y")

That would omit the leading zeros, and would let you use your DATE_FORMAT settings variable or other predefined options.

Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83
0

Maybe override the admin:

Say, the model is called PersonDetail, then in admin.py

class PersonDetailAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.DateTimeField: {'input_formats': ('%m/%d/%Y',)},
    }
user2707389
  • 817
  • 6
  • 12
  • 1
    That affects what input formats the admin understands, but the field would still be stored as a date or datetime and rendered using the implied `str` when string interpolated. – Peter DeGlopper Nov 26 '13 at 22:44
  • Got it. I has used something like that on a form field, and thought it would work. Thanks !! – user2707389 Nov 26 '13 at 22:46