None

Django ModelForm date format

December 21, 2009

I have a Django ModelForm, defined like this:

class DateRangeForm(forms.ModelForm):
    class Meta:
        model = DateRange
        fields = ('item', 'start_date', 'end_date',)

In order to change the date format from the default mm/dd/yyyy, I need to specify a widget for the form element, and put a format on that. But how do I do that, as I'm using a ModelForm and not specifying individual form fields?

You can specify form fields manually - if these have the same name as fields from the model object, then they will override those from the model.

class DateRangeForm(forms.ModelForm):
    start_date = forms.DateField(widget=forms.DateInput(format = '%d/%m/%Y'), 
                                 input_formats=('%d/%m/%Y',))
    end_date = forms.DateField(widget=forms.DateInput(format = '%d/%m/%Y'), 
                               input_formats=('%d/%m/%Y',), 
                               required=False)

    class Meta:
        model = DateRange
        fields = ('item', 'start_date', 'end_date',)

Note the use of required=False on the end_date. The end date is optional on the model, but as we have overridden the auto generated form fields, we need to also specify here that it is not a required field.