Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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.

The option "input_formats" is not recognized.

Thank you!

like image 416
jartymcfly Avatar asked Jun 18 '15 09:06

jartymcfly


People also ask

What is the format of Django DateField?

Python django format date dd/mm/yyyy And, because the format is dd/mm/yyyy, we must use a slash to separate the date, month and year.

How do I change the date format in Django REST framework?

Or you can write custom field and use it instead of default. class UserSerializer(serializers. ModelSerializer): created_at = serializers. DateTimeField(format='%Y') # add read_only=True to the field in case if date created automatically ...

What is Django default datetime format?

django default date to be in format %d-%m-%Y.


2 Answers

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

In settings.py set DATE_INPUT_FORMATS as below:

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 
like image 160
Vaulstein Avatar answered Sep 28 '22 04:09

Vaulstein


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

like image 21
bruno desthuilliers Avatar answered Sep 28 '22 04:09

bruno desthuilliers