How can I set a DateField format in django from the model?

Each Answer to this Q is separated by one/two green lines.

I am creating a django application and I have the next problem: this error is shown when I want to set a date:

ValidationError [u"'12/06/2012' value has an invalid date format. It must be in YYYY-MM-DD format."]

For this model:

class ModelA(models.Model):

    date1 = models.DateField(null=True)
    date2 = models.DateField(null=True)

How can I set the DateField format to be %m/%d/%Y.

The option "input_formats" is not recognized.

Thank you!

As @bruno as mentioned in his answer, input_formats is a forms field, however it can be used to control the date format saved from the model.

In set DATE_INPUT_FORMATS as below:


And in your form you could do something like below:

class ClientDetailsForm(ModelForm):
    date_of_birth = DateField(input_formats=settings.DATE_INPUT_FORMATS)
    class Meta:
       model = ModelA

input_formats is a forms.DateField option, not a model.DateField option. You have to set it in your form, not in your models.

You could also use the LANGUAGE_CODE to get the correct date formate for the local.
Then have DATE_INPUT_FORMATS = ['%d-%m-%Y', '%Y-%m-%d'] in the which can be called when needed at anytime.

date_birth = forms.DateField(label="Date of birth", widget=forms.SelectDateWidget(years=YEAR_CHOICES, input_formats= DATE_INPUT_FORMATS))

In, insert:

USE_L10N = False

DATE_INPUT_FORMATS = ['%d/%m/%Y']  
  • DATE_INPUT_FORMATS’s data type must be a list, containing the format as a string.
  • %d/%m/%Y is just my format of choice.

As of lately(jan 2022), does not contain USE_L10N by default (neither DATE_INPUT_FORMATS, but this one is expected not the be there, I guess).
It seems like, although USE_L10N isn’t there by default, not only it does exists somewhere but it’s also set to True, because setting up DATE_INPUT_FORMATS alone (i.e. without making USE_L10N explicitly False) will not do the trick.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .