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

谁说我不能喝 提交于 2019-12-18 11:08:12

问题


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!


回答1:


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

In settings.py set DATE_INPUT_FORMATS as below:

DATE_INPUT_FORMATS = ['%d-%m-%Y']

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



回答2:


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



来源:https://stackoverflow.com/questions/30911612/how-can-i-set-a-datefield-format-in-django-from-the-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!