Django表单:在DateField上设置初始值

时间:2016-04-27 05:34:05

标签: python django django-forms

我有以下代码来设置DateField和CharField的初始值。 CharField的初始值设置正确,但DateField的初始值仍为空白。

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 个答案:

答案 0 :(得分:7)

您可以在创建DateField的同一行中设置默认值:

date = forms.DateField(initial=datetime.date.today)

或者如果您想要传递特定日期,您可以创建一个函数并将其传递给DateField,如下所示:

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)
    #...

此外,您可以查看docs以获取更多帮助;)