django中如何在shell里面测试Form?


比如,我有如下Form,

class MyForm1(forms.ModelForm):
   # As you can see, we have to define label and help_text again in the form when
   # all we really want to change, in this case, is the widget
   myfield1 = forms.CharField( label=”My Field 1 Name”, help_text=”My Field 1 help”,
                                                  widget=forms.Textarea(attrs={‘class’:’myclass’,}))
   class Meta:
       model = models.MyModel

现在想直接在shell做一个测试,请问该如何操作?

form 开发 django shell

skean 9 years, 10 months ago

你可以模拟数据被POST到表单。 比较容易的方法,就是根据需要POST的数据,创建一个key/value的dict(字典)。具体代码如下:

>>> from a.forms import MyForm1
>>> post_or_get_data = {u'myfield1':[u'a'], u'myfield2':[u'b']}
>>> f = MyForm1(data=post_or_get_data)
>>> f
<a.forms.myform1 object="" at="" 0x969284c="">
>>> f.is_bound
True
>>> f.is_valid()
True
>>> f.errors
{}
>>> f.data
{u'myfield2': [u'b'], u'myfield1': [u'a']}
>>> f.cleaned_data
{'myfield2': u"[u'b']", 'myfield1': u"[u'a']"}

请注意,只有当 isvalid()函数被调用后,cleaneddata才会被生成。否则会报错,

'MyForm1' object has no attribute 'cleaned_data'

法律意识恶劣的 answered 9 years, 10 months ago

Your Answer