I am trying to setup a Model and a corresponding ModelForm with django containing a DateField/Input.
from django.db import models
class MyModel(models.Model):
myDate = models.DateField()
from django import forms
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = "__all__"
widgets = {
'myDate': forms.DateInput(format=("%d/%m/%Y"))
}
But sadly, when I enter a date in the form that results out of MyModelForm, the day and the month get exchanged. E.g. 1/2/22 will result in January 2nd 2022 instead of feburary 1st 2022. What else do I need to do, so the date gets interpreted properly?
CodePudding user response:
Specifying the format only in your widget’s form is just used as a display, you still need to pass it to specify the field myDate
as a DateField
in your form:
from django.db import models
class MyModel(models.Model):
myDate = models.DateField()
from django import forms
class MyModelForm(forms.ModelForm):
myDate = forms.DateField(input_formats=["%d/%m/%Y"])
class Meta:
model = MyModel
fields = "__all__"
widgets = {
'myDate': forms.DateInput(format=("%d/%m/%Y"))
}
Another option to set this up would be to add the format inside the DATE_INPUT_FORMAT
variable in settings.py
. See https://docs.djangoproject.com/en/4.0/ref/settings/#date-input-formats for more