在处理动态表单集时,有时TOTAL_FORMS大于实际的表单数。而且,用户可以很容易地修改这个输入TOTAL_FORMS。
例如,我的输入是
<input name='user-TOTAL_FORMS' type='hidden' value='5'/>
然而,这里只显示了2个实际的表单。
在这种情况下,Django在formset中生成不需要的空表单。形式变量。如果有任何验证错误并且再次显示表单,则会产生问题。Page显示了那些不需要的表单。(在示例中,应该只显示2个实际表单,但由于总数为5,因此用户总共看到5个表单)
如何删除这些不需要的表单,更新总数并使用更新的表单集重新显示表单?
编辑:具有挑战性的部分是在删除表单时也要更新索引。因此表单总数与最后一个表单索引匹配。
这是一个老问题,我不确定Django是否已经改变了很多。但我最终这样做的方式是写一个函数来更新表单集数据。这里的关键是首先复制表单集数据(QueryDict)。下面是代码:
def updateFormDataPrefixes(formset):
"""
Update the data of the formset to fix the indices. This will assign
indices to start from 0 to the length. To do this requires copying
the existing data and update the keys of the QueryDict.
"""
# Copy the current data first
data = formset.data.copy()
i = 0
nums = []
for form in formset.forms:
num = form.prefix.split('-')[-1]
nums.append(num)
# Find the keys for this form
matched_keys = [key for key in data if key.startswith(form.prefix)]
for key in matched_keys:
new_key = key.replace(num, '%d'%i)
# If same key just move to the next form
if new_key == key:
break
# Update the form key with the proper index
data[new_key] = data[key]
# Remove data with old key
del data[key]
# Update form data with the new key for this form
form.data = data
form.prefix = form.prefix.replace(num, '%d'%i)
i += 1
total_forms_key = formset.add_prefix(TOTAL_FORM_COUNT)
data[total_forms_key] = len(formset.forms)
formset.data = data
Lol,这仍然是一个老问题,但真正的答案是"添加extra=0
属性,因为默认的extra
定义是3"
LinkFormSet = inlineformset_factory(
ParentModel,
ChildModel,
fields = ('price', 'deadline',),
extra=0
)
更多文档可在这里获得:https://docs.djangoproject.com/en/2.1/ref/forms/models/#django.forms.models.inlineformset_factory