0

In the following unit test (which uses factory_boy test fixtures),

class PackageDefaultTest(TestCase):
    def test_1(self):
        company = CompanyFactory()
        package = PackageFactory(company=company)
        form = PackageForm(instance=package)
        import ipdb; ipdb.set_trace()

after dropping into the debugger, I encounter the following strange situation:

> /Users/kurtpeek/Documents/Dev/lucy/lucy-web/dashboard/tests/test_packages.py(601)test_1()
    599         package = PackageFactory(company=company)
    600         form = PackageForm(instance=package)
--> 601         import ipdb; ipdb.set_trace()

ipdb> form.is_valid()
False
ipdb> form.errors
{}

That is, form.is_valid() is False, but form.errors is an empty dictionary. Can someone explain how this is possible? From what I understand from https://docs.djangoproject.com/en/2.0/ref/forms/api/#using-forms-to-validate-data, no errors implies a valid form.

Kurt Peek
  • 52,165
  • 91
  • 301
  • 526
  • 3
    The form is not bound to any data so it is not valid. If you try `form = PackageForm(instance=package, data={})` then you'll get some errors. – Alasdair Mar 22 '18 at 17:08
  • Indeed, this is the situation described in https://docs.djangoproject.com/en/2.0/ref/forms/api/#behavior-of-unbound-forms. It would appear from the source code for [`BaseModelForm`](https://github.com/django/django/blob/a2e97abd8149e78071806a52282a24c27fe8236b/django/forms/models.py) that the `instance` is passed to the form's `initial`, not its `data`. In my case, I do want the `package` instance to provide data for the form, so I did `form = PackageForm(data=model_to_dict(package))`. – Kurt Peek Mar 22 '18 at 17:30

0 Answers0