我有一个表单工厂,它根据从MailChimp API返回的数据动态构建表单。我正在为表单可能使用的每种类型的小部件构建一个测试用例(选择,无线电和复选框)。现在我在字段的str()
表示中搜索子字符串,但是,我假设有一种方法可以直接确定类型?
GroupsForm = groups_form_factory()
form = GroupsForm()
for field in form:
self.assertIn('type="checkbox"', str(field),
"Form field should be represented by a checkbox.")
# this works, but, isn't there a way to check the field's widget type?
答案 0 :(得分:4)
使用type(field.field.widget)
BoundField
在django.forms
中定义。
答案 1 :(得分:0)
>>> from myapp.forms import RestaurantReviewForm
>>> f = RestaurantReviewForm()
>>> from django.forms.widgets import TextInput
>>> for field in f: print type(field.field.widget), isinstance(field.field.widget, TextInput)
...
<class 'django.forms.widgets.TextInput'> True
<class 'django.forms.widgets.TextInput'> True
<class 'django.forms.widgets.TextInput'> True
<class 'django.forms.widgets.TextInput'> True
<class 'django.forms.widgets.TextInput'> True
<class 'django.forms.widgets.CheckboxInput'> False
<class 'django.forms.widgets.Select'> False
<class 'django.forms.widgets.Textarea'> False
<class 'captcha.fields.CaptchaTextInput'> False