我有一个子类
ModelForm
,
FamilyDemographicsForm
,其中两个
ChoiceField
需要:
point_of_contact
和
birth_parent
. 例如,以下测试通过:
class FamilyDemographicsFormTest(TestCase):
def test_empty_form_is_not_valid(self):
'''The choice fields 'point_of_contact' and 'birth_parent' are
the only two required fields of the form'''
form = FamilyDemographicsForm(data={})
# The form is not valid because the required fields have not been provided
self.assertFalse(form.is_valid())
self.assertEqual(form.errors,
{'point_of_contact': ['This field is required.'],
'birth_parent': ['This field is required.']})
def test_form_with_required_fields_is_valid(self):
'''The form's save() method constructs the expected family'''
data = {'point_of_contact': Family.EMPLOYEE,
'birth_parent': Family.PARTNER}
form = FamilyDemographicsForm(data=data)
self.assertTrue(form.is_valid())
# The family returned by saving the form has the expected attributes
family = form.save()
self.assertEqual(family.point_of_contact, Family.EMPLOYEE)
self.assertEqual(family.birth_parent, Family.PARTNER)
# The family exists in the database
self.assertTrue(Family.objects.filter(id=family.id).exists())
在第二个测试用例中
Family
创建于
form.save()
. 我想尝试更新现有的族。为了让我开始,我尝试了以下方法:
def test_update_existing_family(self):
initial = {'point_of_contact': Family.EMPLOYEE,
'birth_parent': Family.PARTNER}
data = {'employee_phone': '4151234567',
'employee_phone_type': Family.IPHONE,
'partner_phone': '4157654321',
'partner_phone_type': Family.ANDROID}
form = FamilyDemographicsForm(data=data, initial=initial)
import ipdb; ipdb.set_trace()
然而,当我进入调试器时,我注意到
form.is_valid()
是
False
和
form.errors
表示未提供必填字段:
ipdb> form.errors
{'point_of_contact': ['This field is required.'], 'birth_parent': ['This field is required.']}
我的问题是:有什么方法可以实例化一个有效的
模型形式
具有
data
是否不包括必填字段?E、 g.通过提供适当的
initial
或
instance
论点(我从的源代码中还不清楚这一点
BaseModelForm
在…上
https://github.com/django/django/blob/master/django/forms/models.py
).