Django表单:在DateField上设置初始值 [英] Django form: setting initial value on DateField
本文介绍了Django表单:在DateField上设置初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码来设置DateField和CharField的初始值.CharField的初始值已正确设置,但DateField的初始值仍为空白.
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'
推荐答案
您可以在创建DateField的同一行中设置默认值:
You can set the default value in the same line where you're creating the DateField:
date = forms.DateField(initial=datetime.date.today)
或者,如果您希望传递特定的日期,则可以创建一个函子并将其传递给DateField,如下所示:
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)
#...
此外,您可以查看docs 以获得更多帮助;)
In addition, you could review the docs for more help on this ;)
这篇关于Django表单:在DateField上设置初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文