Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用clean更改Django表单集中的字段_Python_Django_Forms_Inline Formset_Formsets - Fatal编程技术网

Python 使用clean更改Django表单集中的字段

Python 使用clean更改Django表单集中的字段,python,django,forms,inline-formset,formsets,Python,Django,Forms,Inline Formset,Formsets,如何使用clean方法更改Django表单集每个表单中的字段 class MyInlineFormSet(BaseInlineFormSet): def clean(self): if self.cleaned_data['inputted'] == self.cleaned_data['answer']: self.cleaned_data['is_correct'] = True return self.cleaned_dat

如何使用
clean
方法更改Django表单集每个表单中的字段

class MyInlineFormSet(BaseInlineFormSet):

    def clean(self):
        if self.cleaned_data['inputted'] == self.cleaned_data['answer']:
            self.cleaned_data['is_correct'] = True
        return self.cleaned_data
这不起作用,我见过人们迭代每个表单,但他们只验证而不更改。如果我迭代每个表单,那么如何返回
已清理的\u数据
?换言之:

class MyInlineFormSet(BaseInlineFormSet):

    def clean(self):    
        for form in self.forms:
            if form.cleaned_data['inputted'] == form.cleaned_data['answer']:
                form.cleaned_data['is_correct'] = True
        ...?

我相信,通过迭代每个表单并设置清理后的数据(您的第二个示例),您已经走上了正确的道路。BaseFormSet有一个名为
cleaned_data
的属性,该属性返回每个表单的已清理数据列表。这就是你想要的吗?例如:

return self.cleaned_data
它从字面上返回:

[form.cleaned_data for form in self.forms]
如果我正确读取代码,那么应该有正确的数据(修改后)

如果您只想在模型中保存值,我建议您避免使用
clean
方法,而是覆盖
save
方法:

def save_new(self, form, commit=True):
    form.instance.is_correct = ...
    return super(...).save_new(...)

def save_existing(...)

基于ssomnoremac注释,我在BaseModelFormSet清理方法中使用了form.instance.field\u I\u wanted\u to\u change,而不是form.cleaned\u data['field\u I\u wanted\u to\u change'],它成功了。差不多

class MyInlineFormSet(BaseInlineFormSet):

def clean(self):
    for form in self.forms:
        if form.cleaned_data['inputted'] == form.cleaned_data['answer']:
            form.instance.is_correct = True
在我的例子中,我已经调用了clean\u field\u我希望\u改变,所以顺序是clean\u field>clean@MyInlineFormSet
Django 1.11

David,谢谢。关于self.u数据,您的答案是正确的,但这仍然没有改变字段。问题已经解决,因为数据只是访问器而不是修改器。我需要的是:“form.instance.is_correct=True”form.instance实际上修改了文档中解释的字段[添加到我的答案中。我很高兴你能理解这一点,我认为这是一个有用的问题,因为内联表单的处理方式需要与普通表单稍有不同。如果我的答案没有说明你想要什么,请随意提交你自己的答案。