问题
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'
回答1:
You can set the default value in the same line where you're creating the DateField:
date = forms.DateField(initial=datetime.date.today)
Or if you want to pass a specific date, you could create a funciton and pass it to the DateField, as follows:
def my_date():
return datetime.date(year=today.year-1, month=today.month, day=today.day)
class MyForm(forms.ModelForm):
#...
date = forms.DateField(initial=my_date)
#...
In addition, you could review the docs for more help on this ;)
来源:https://stackoverflow.com/questions/36881089/django-form-setting-initial-value-on-datefield