Problems with the Model.DateField format

I have a model that has a date field

date_of_birth = models.DateField(blank=True, null=True, verbose_name="DOB")

I would like to format it to save the dates in a format dd/MM/yyyy, but everything I tried fails.

I think that should be by default YYYY-MM-ddbecause it saves my database. Trying to send dates in a different format gives an error:

[u"'17/01/1970' value has an invalid date format. It must be in YYYY-MM-DD format."]

I tried using Date Widgets , but I have several issues related to its compatibility with my machines.

+4
source share
3 answers

, input_formats DateField . . :

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

['%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'

, .

, %d/%m/%y, .

+5

DateField , , , . , :

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

parseDate , .

+1

input_formats , . ModelForm / , , .

"[...] you need full control over the field, you can do this by declaratively specifying the fields, as in the usual form." Here is 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")
0
source

Source: https://habr.com/ru/post/1568016/


All Articles