如何使用clean
方法更改Django formset的每个形式中的字段?在
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
这是行不通的,我见过人们迭代每个表单,但他们只验证而不更改。如果我迭代每个表单,那么如何返回cleaned_data
?换句话说:
根据ssomnoremac的评论,我用form.instance.field\u希望更改在BaseModelFormSet clean方法中,而不是已清理的数据['field\u i'u want_u to_change']而且成功了。有点像
在我的例子中,我已经打电话给clean_field_I_want_change,因此顺序是clean_field>;clean@MyInlineFormSet 迪亚戈1.11
我相信通过迭代每个表单并设置清理后的数据(您的第二个示例),您的思路是正确的。BaseFormSet有一个名为
cleaned_data
的属性,它返回每个窗体的已清理数据的列表。这就是你想要的吗?E、 g.:它实际上返回:
^{pr2}$如果我正确地读取代码,它应该有正确的数据(修改后)。在
如果您只对在模型中保存值感兴趣,我建议您避免使用
clean
方法,而是重写save
方法:相关问题 更多 >
编程相关推荐