I have the following code to set the initial value for a DateField and CharField. CharField's initial value got set properly, but the DateField's initial value is still blank.
class MyForm(forms.ModelForm):
dummy = fiscal_year_end = forms.CharField()
date = forms.DateField()
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
today = datetime.date.today()
new_date = datetime.date(year=today.year-1, month=today.month, day=today.day)
self.fields["date"].initial = new_date
self.fields["dummy"].initial = 'abc'
I'm not sure this is answering the (not 100% clear) initial question, but I got here so here's my solution.
The HTML value
attribute of the date field contained the date, but formatted in a way that depended on the language, and was never the expected one. Forcing the date to ISO format did the trick:
class MyForm(forms.ModelForm):
my_date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}))
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.initial['my_date'] = self.instance.my_date.isoformat() # Here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With