Search code examples
djangodjango-formsdjango-widget

django: SplitDateTimeWidget ignores date_format


I am trying to use the SplitDateTimeWidget but want it to accept date in day - month - year format.

from django.forms.widgets import SplitDateTimeWidget

class EventForm(forms.ModelForm):
    class Meta:
        model = Event
        widgets = {'start': SplitDateTimeWidget(date_format='%d/%m/%Y')}

The SplitDateTimeWidget accepts a date_format argument, which I expect to be used to validate the date input but it isn't.

The default widget is correctly replaced but it ignores the date_format and insists on validating against the default month - day - year.

I also tried setting the DATE_FORMAT and DATE_INPUT_FORMATS settings with no luck.

Thanks for any help.


Solution

  • Widget date format responsible only for output and does not matter for validation. What matters is field type, and in case of SplitDateTimeField it uses DateField and TimeField which are instantiated using input_date_formats parameter.

    So the answer is:

    class EventForm(forms.ModelForm):
        class Meta:
            model = Event
            widgets = {'start': SplitDateTimeWidget(date_format='%d/%m/%Y')}
    
        start = SplitDateTimeField(input_date_formats='d/m/Y',
                                   input_time_formats='<whatever, or skip it>')
    

    Note that input_date_formats is a Django format, http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date