Search code examples
pythondjangomodelformfactory-boy

Django 1.7 modelform_factory form is always invalid with factory_boy created model


I'm using Django 1.7 and factory_boy to create some models. Here's the code:

In models.py:

class Address(models.Model):
    first_line = models.CharField(max_length=50, blank=True)
    second_line = models.CharField(max_length=50, blank=True)
    city = models.CharField(max_length=30, blank=True)
    state = models.CharField(max_length=2, blank=True)
    zipcode = models.CharField(max_length=5, blank=True)
    zipcode_ext = models.CharField(max_length=4, blank=True)

The associated factory in factories.py (same directory):

class AddressFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Address

    first_line = "555 Main St."
    second_line = "Unit 2"
    city = "Chicago"
    state = "IL"
    zipcode = "60606"
    zipcode_ext = "1234"

Now, given this code in the django shell:

>>> from models import Address
>>> from django.forms.models import modelform_factory
>>> AddressForm = modelform_factory(Address)
>>> from factories import AddressFactory
>>> a = AddressFactory.create()
>>> af = AddressForm(instance = a)
>>> af.is_valid()
False

For some reason, the call to is_valid seems to always return false, and I can't figure out why. There don't seem to any errors on the form, and clean(), clean_fields(), and validate_unique() all do not seem to raise errors on the instance.

Why does is_valid always return false?


Solution

  • This has nothing to do with factory_boy. Forms are always invalid if they don't have any data, which yours doesn't. The instance parameter is used to populate the form's initial data for display, and to determine the object ID for updating, but it isn't used to set that data on POST.

    I'm not quite sure what you want to do with the form there, but you'd need to convert it to a POST dictionary and pass it to the form's data parameter for it to be valid.