Models.DateField Format issues

半腔热情 提交于 2019-12-03 16:29:53

You can change this by overriding input_formats on the DateField in your form. This is covered pretty well in the documentation. The default date formats are

['%Y-%m-%d',      # '2006-10-25'
'%m/%d/%Y',       # '10/25/2006'
'%m/%d/%y']       # '10/25/06'

or

['%Y-%m-%d',      # '2006-10-25'
'%m/%d/%Y',       # '10/25/2006'
'%m/%d/%y',       # '10/25/06'
'%b %d %Y',      # 'Oct 25 2006'
'%b %d, %Y',      # 'Oct 25, 2006'
'%d %b %Y',       # '25 Oct 2006'
'%d %b, %Y',      # '25 Oct, 2006'
'%B %d %Y',       # 'October 25 2006'
'%B %d, %Y',      # 'October 25, 2006'
'%d %B %Y',       # '25 October 2006'
'%d %B, %Y']      # '25 October, 2006'

Depending on whether or not you are using localization in your settings.

You appear to be looking for %d/%m/%y, which isn't a default format.

One option would be to extend DateField to handle other date formats, such as by converting them yourself during the save, instructions here. For reference, I just had to deal with this problem and my solution looked like this:

class HWDateField(models.DateField):
def to_python(self, value):
    if value is None:
        return value
    return super(HWDateField,self).to_python(parseDate(value))

Where parseDate was a conversion function I had already written.

You can not set the input_formats on the model's field, but only on the form's field. With a ModelForm, and fields auto generated based on the model, you redefine/customize what you need as documented here.

"[...] you want complete control over of a field, you can do this by declaratively specifying fields like you would in a regular Form.". Here's my example :

class UserCreationForm(BaseUserCreationForm):
    birth_date = forms.DateField(input_formats=['%d/%m/%Y'])

    class Meta(BaseUserCreationForm.Meta):
        model = User
        fields = ("username", "first_name", "last_name", "email", "birth_date")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!