Django form: setting initial value on DateField

寵の児 提交于 2020-12-08 07:04:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!