2

我试图在表单集的每种形式中使用 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 函数中引发错误)。

4

1 回答 1

1

好的,我刚刚弄清楚发生了什么(哇,我很愚蠢)。发生错误是因为我将 tags.required 设为 False 但调用 saveTags 时不知道该特定表单是否有任何输入值。简单的解决方法是检查cleaned_data dict是否为空:

if tags_formset.is_valid():
    for tagForm in tags_formset.forms:
        #check if cleaned_data is non-empty
        if tagForm.cleaned_data:
            tagForm.saveTags()
于 2013-04-17T01:06:45.480 回答