我有一个模式Map1有2个字段,我试图使用这个Map1初始化formset。当我初始化名称和位置时,它没有初始化,它要求id值但是当给出id值时我得到以下错误。
class Map1(models.Model):
name = models.CharField(max_length=128)
position = ArrayField(models.IntegerField(), size=2)
class Meta:
unique_together = (('name', 'position'))
modelformset = modelformset_factory(Map1, fields=('name', 'position'))
>>> data = {
... 'form-TOTAL_FORMS': '1', # the number of forms rendered
... 'form-INITIAL_FORMS': '1', # the number of forms with initial data
... 'form-MAX_NUM_FORMS': '', # the max number of forms
... 'form-0-id': 1,
... 'form-0-name': 'germantown',
... 'form-0-position': '10,20',
... }
>>> formset = modelformset(data=data)
>>> formset.errors
[{'id': ['Select a valid choice. That choice is not one of the available choices.']}]
如果我删除了form-id,我会收到此错误 -
>>> data = {
... 'form-TOTAL_FORMS': '1', # the number of forms rendered
... 'form-INITIAL_FORMS': '1', # the number of forms with initial data
... 'form-MAX_NUM_FORMS': '', # the max number of forms
...
... 'form-0-name': 'germantown',
... 'form-0-position': '10,20',
... }
>>> formset = modelformset(data=data)
>>> formset.errors
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/premanandlakshmanan/Documents/django-contribute/django/django/forms/formsets.py", line 295, in errors
self.full_clean()
File "/Users/premanandlakshmanan/Documents/django-contribute/django/django/forms/formsets.py", line 343, in full_clean
form = self.forms[i]
File "/Users/premanandlakshmanan/Documents/django-contribute/django/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/premanandlakshmanan/Documents/django-contribute/django/django/forms/formsets.py", line 144, in forms
for i in range(self.total_form_count())]
File "/Users/premanandlakshmanan/Documents/django-contribute/django/django/forms/formsets.py", line 144, in <listcomp>
for i in range(self.total_form_count())]
File "/Users/premanandlakshmanan/Documents/django-contribute/django/django/forms/models.py", line 588, in _construct_form
pk = self.data[pk_key]
KeyError: 'form-0-id'