Django 1.7 modelform_factory 表单对于 factory_boy 创建的模型总是无效的
Django 1.7 modelform_factory form is always invalid with factory_boy created model
我正在使用 Django 1.7 和 factory_boy 创建一些模型。这是代码:
在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)
factories.py中的关联工厂(同一目录):
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"
现在,在 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
出于某种原因,对 is_valid 的调用似乎总是 return 错误,我不明白为什么。表单上似乎没有任何错误,clean()、clean_fields() 和 validate_unique() 似乎都不会在实例上引发错误。
为什么 is_valid 总是 return 错误?
这与factory_boy无关。如果表单没有任何数据,那么它们总是无效的,而你的则没有。 instance
参数用于填充表单的 初始 数据以供显示,并确定要更新的对象 ID,但它不用于在 POST.
我不太确定你想用那里的表格做什么,但你需要将它转换成 POST 字典并将它传递给表格的 data
参数它是有效的。
我正在使用 Django 1.7 和 factory_boy 创建一些模型。这是代码:
在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)
factories.py中的关联工厂(同一目录):
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"
现在,在 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
出于某种原因,对 is_valid 的调用似乎总是 return 错误,我不明白为什么。表单上似乎没有任何错误,clean()、clean_fields() 和 validate_unique() 似乎都不会在实例上引发错误。
为什么 is_valid 总是 return 错误?
这与factory_boy无关。如果表单没有任何数据,那么它们总是无效的,而你的则没有。 instance
参数用于填充表单的 初始 数据以供显示,并确定要更新的对象 ID,但它不用于在 POST.
我不太确定你想用那里的表格做什么,但你需要将它转换成 POST 字典并将它传递给表格的 data
参数它是有效的。