如何从模型中设置django中的DateField格式?

时间:2022-02-16 20:16:39

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

我正在创建一个django应用程序,我的下一个问题是:当我想设置日期时,会显示这个错误:

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.

如何将DateField格式设置为%m/%d/%Y。

The option "input_formats" is not recognized.

选项“input_formats”不被识别。

Thank you!

谢谢你!

2 个解决方案

#1


8  

In settings.py set DATE_INPUT_FORMATS as below:

在设置。py设置date_input_format如下:

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


13  

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

input_formats形式。DateField选项,不是模型。DateField选项。你必须把它设置成你的形式,而不是你的模型。

#1


8  

In settings.py set DATE_INPUT_FORMATS as below:

在设置。py设置date_input_format如下:

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


13  

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

input_formats形式。DateField选项,不是模型。DateField选项。你必须把它设置成你的形式,而不是你的模型。