February 2011

archive

change the default formating of the DateField in django forms Feb
23
1
1

Django forms are great, but sometimes you need to do a little work to get things just the way you want. The DateField has an easy way to restrict how data is entered through the input_formats option; but unless if I'm missing something there's isn't a similar way to help you set how the field displays the date in the template.

The default way the forms.DateField is displayed is YYYY-MM-DD, which is typically not what you want to present to the users.

The easiest way I have found to change how the date field displays is to write a small custom form field that inherits from forms.DateField that overrides the widget.

It would look something like this:

from django import forms
from django.utils.translation import ugettext_lazy as _


class FormattedDateField(forms.DateField):
    widget = forms.DateInput(format='%m/%d/%Y')

    def __init__(self, *args, **kwargs):
        super(FormattedDateField, self).__init__(*args, **kwargs)
        self.input_formats = ('%m/%d/%Y',)


class ProfileForm(forms.Form):
    email = forms.EmailField()
    first_name = forms.CharField(max_length=100)
    last_name = forms.CharField(max_length=100)
    birthday = FormattedDateField()

Or for a short-hand version that doesn't require overriding the form class could look something like the following:

class ProfileForm(forms.Form):
    email = forms.EmailField()
    first_name = forms.CharField(max_length=100)
    last_name = forms.CharField(max_length=100)
    birthday = forms.DateField(widget=forms.DateInput(format='%m/%d/%Y')), input_formats=('%m/%d/%Y',))

Now, when I initialize the birthday field in the form instead of displaying YYYY-MM-DD, it will look like MM/DD/YYYY which is more natural to an American audience.

comments