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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30911612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:09:17  来源:igfitidea点击:

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

pythondjangoformatdatefield

提问by jartymcfly

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!

谢谢!

采纳答案by Vaulstein

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

正如@bruno 在他的回答中提到的,input_formats是一个表单字段,但它可用于控制从模型中保存的日期格式。

In settings.pyset DATE_INPUT_FORMATSas below:

settings.py设置DATE_INPUT_FORMATS如下:

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

回答by bruno desthuilliers

input_formatsis a forms.DateFieldoption, not a model.DateFieldoption. You have to set it in your form, not in your models.

input_formats是一种forms.DateField选择,而不是一种model.DateField选择。你必须在你的表单中设置它,而不是在你的模型中。

回答by Ibby

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

您还可以使用 LANGUAGE_CODE 为本地获取正确的日期格式。 LANGUAGE_CODE ='en-GB'然后DATE_INPUT_FORMATS = ['%d-%m-%Y', '%Y-%m-%d']settings.py需要的时候随时调用。

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

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