【问题标题】:Form's cleaned_data is empty but formset's cleaned_data isnt?表单cleaned_data 是空的,但formsetclean_data 不是?
【发布时间】:2013-04-09 14:25:31
【问题描述】:

我试图在表单集的每个表单中使用 CharField 中的字符串值,但是由于某种原因,每个表单的清理数据总是显示为空,而表单集的清理数据不是。这是我的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 函数中引发错误)。

【问题讨论】:

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


    【解决方案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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-14
      • 2021-10-19
      • 1970-01-01
      • 2019-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多