我试图在表单集的每种形式中使用 CharField 中的字符串值,但是由于某种原因,每个表单的 clean_data 总是显示为空,而表单集的清理数据不是。这是我的views.py中的代码:
TagsFormSet = formset_factory(TagsForm, formset=TagFormSet, extra=applicantQuery.count())
if request.method == 'POST':
tags_formset = TagsFormSet(request.POST, request.FILES, prefix='tags', applicants=applicantQuery)
if tags_formset.is_valid():
for tagForm in tags_formset.forms:
tagForm.saveTags()
我的表格如下所示:
class TagFormSet(BaseFormSet):
def __init__(self, *args, **kwargs):
applicants = kwargs.pop('applicants')
super(TagFormSet, self).__init__(*args, **kwargs)
#after call to super, self.forms is populated with the forms
#associating first form with first applicant, second form with second applicant and so on
for index, form in enumerate(self.forms):
form.applicant = applicants[index]
class TagsForm(forms.Form):
tags = forms.CharField()
def __init__(self, *args, **kwargs):
super(TagsForm, self).__init__(*args, **kwargs)
self.fields['tags'].required = False;
def saveTags(self):
Tag.objects.update(self.applicant, self.cleaned_data['tags'])
正如我之前所说,tags_formset.cleaned 数据包含在页面上输入的正确信息,但是表单的清理数据是空的。这段代码给了我一个 KeyValue 错误,说“标签”不在已清理的数据中,因为它没有任何内容(在 saveTags 函数中引发错误)。