Django datetimefield invalid for certain locales

332 views Asked by At

I don't have any date input formats defined, my form field is:

    expiry_date = forms.DateTimeField(widget=SelectDateWidget,
                                      required=False)

I'm using the locales en (English) and zh-hans (Simplified Chinese).

According to PyCharm debugger, the POST values are identical in either language:

self.request.POST['expiry_date_day'] = u'25'
self.request.POST['expiry_date_month'] = u'9'
self.request.POST['expiry_date_year'] = u'2015'

However I get the error only in zh-hans.

In the form.clean() method the self.cleaned_data['expiry_date'] value is missing, so I'm guessing it's being stripped out due to failing a previous validation error.

Fixed:

I fixed this by adding the following to my settings:

DATE_INPUT_FORMATS = ('%Y-%m-%d', '%Y/%m/%d')

And then apply this to the specific DateTimeField:

expiry_date = forms.DateTimeField(widget=SelectDateWidget,
                                  input_formats=settings.DATE_INPUT_FORMATS,
                                  required=False)

Specifically '%Y-%m-%d' is needed to keep en happy, whilst '%Y/%m/%d' allows zh-hans and zh-hant to function correctly.

I found this by drilling down in the debugger and figuring out what value was passing though DateTimeField.to_python().

I'll leave the question open though, as I'd still like to understand exact why they are formatted differently by locale, and if there's a more obvious way to figure out which formats to allow and when and I don't think the solution should be "step-through the debugger until you find the line of code!"

0

There are 0 answers