表格cleaning_data是空的,但formset cleaning_data不是?

时间:2013-04-17 00:52:42

标签: django forms django-forms formsets cleaned-data

我试图在每种形式的formset中使用CharField中的String值,但是由于某种原因,每个表单的cleaning_data总是显示为空,而formset的清理数据则不是。这是我的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错误,说'tags'不在清理数据中,因为它没有任何内容(saveTags函数中抛出错误)。

1 个答案:

答案 0 :(得分:1)

好的,我只知道发生了什么(哇,我笨)。发生错误是因为我使tags.required False,但如果该特定表单有任何输入值,则调用saveTags。简单的解决方法是检查cleaning_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()