开发者

how to change default dateformat AAAA-MM-DD to dd/mm/yyyy in Django?

开发者 https://www.devze.com 2022-12-10 18:36 出处:网络
My locale dateformat is dd/mm/yyyy and Django is requering AAAA-MM-DD when the user inputs 04/11/2009 Django raises:

My locale dateformat is dd/mm/yyyy and Django is requering AAAA-MM-DD

when the user inputs 04/11/2009 Django raises:

_('Enter a valid date in YYYY-MM-DD format.'))开发者_如何学编程 

Im using simple html input field type="text", Not forms.DateField

Thanks :)


I'm assuming you are using a forms.DateField. If so, you need to supply a input_formats argument like so:

class MyForm(forms.Form):
    start_date = forms.DateField(input_formats=['%d/%m/%Y'])

input_formats just takes a list of the formats you want to accept.

See http://docs.djangoproject.com/en/dev/ref/forms/fields/#datefield for more information.


Based on the OP's post and comments, it looks like there is more here than just using input_formats for the date field, though you'll want to do that. The message 'Enter a valid date in YYYY-MM-DD format' is an exception and NOT a form validation error. You'll get this exception if you try to save a model instance using a date string that is not 'YYYY-MM-DD'.

What is needed is to use a DateField in the form, and then instantiate the model using the cleaned data, which is a datetime object. It looks like the OP was instantiating the model with a string rather than a datetime object.

This section of the Django docs discusses preparing DateField data: https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#what-happens-when-you-save

0

精彩评论

暂无评论...
验证码 换一张
取 消