【问题标题】:How to instantiate a Django ModelForm with pre-filled required fields?如何使用预先填写的必填字段实例化 Django ModelForm?
【发布时间】:2018-07-25 17:22:13
【问题描述】:

我有一个ModelFormFamilyDemographicsForm 的子类,其中需要两个ChoiceFieldpoint_of_contactbirth_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()Falseform.errors 表示未提供必填字段:

ipdb> form.errors
{'point_of_contact': ['This field is required.'], 'birth_parent': ['This field is required.']}

我的问题是:有没有办法用不包含必填字段的data 实例化一个有效的ModelForm?例如。通过提供适当的initialinstance 参数? (这在https://github.com/django/django/blob/master/django/forms/models.py 上的BaseModelForm 的源代码中对我来说不是很清楚)。

【问题讨论】:

    标签: python django forms modelform


    【解决方案1】:

    您可以修改 Django 提供的 ModelFormForm 以满足您的需求。您可以根据需要覆盖每个方法。最基本和最重要的预填充是为 initial dict 提供数据 {field_name: value, ...},该表单无需任何修改即可接受。

    所以例如你有这个

    class Model1(models.Model):
        name = models.CharField(max_length=100)
    

    还有这个表格

    class Model1ModelForm(forms.ModelForm):
        class Meta:
            model = Model1
            fields = ('name', )
    

    您可以在视图中提供初始数据

    initial = {'name': 'Initial name'}
    form = Model1ModelForm(initial=initial)
    

    因此,此表格中的名称将被预先填写。

    django 文档:Providing initial values

    堆栈溢出:Pass initial value to a modelform in django

    【讨论】:

      猜你喜欢
      • 2013-04-18
      • 2019-04-04
      • 2012-11-06
      • 2012-10-14
      • 2018-12-24
      • 1970-01-01
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多