我看了http://docs.djangoproject.com/en/dev/ref/forms/fields/
>>> class CommentForm(forms.Form):
... name = forms.CharField(initial='Your name')
... url = forms.URLField(initial='http://')
... comment = forms.CharField()
>>> f = CommentForm(auto_id=False)
>>> print f
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr>
<tr><th>Url:</th><td><input type="text" name="url" value="http://" /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
在我的情况下,我想在views.py中使用初始字段 因为我的初始数据(myinit_data)我在views.py
中得到它my forms.py
#...
class SendMailForm(forms.Form):
to = forms.EmailField(initial=myinit_data, widget = forms.TextInput(attrs={'size': '50'}))
subject = forms.CharField(widget = forms.TextInput(attrs={'size': '50'}))
body = forms.CharField(widget = forms.Textarea(attrs={'cols': '50', 'rows': '10'}), required=False)
my views.py
#....
myinit_data = list_of_data_generated # for example [a@mail.com,b@mail.com,c@mail.com]
form_sendmail = SendMailForm()
我如何从views.py初始化我的字段
谢谢! :)
答案 0 :(得分:3)
如the documentation所述,您可以将初始数据传递给表单构造函数:
form_sendmail = SendMailForm(initial=myinit_data)
但是myinit_data
必须是字典,键是字段名称。