使用clean更改Django formset中的字段

2024-09-30 04:31:24 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用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?换句话说:

^{pr2}$

Tags: django方法selfclean表单dataifdef
2条回答

根据ssomnoremac的评论,我用form.instance.field\u希望更改在BaseModelFormSet clean方法中,而不是已清理的数据['field\u i'u want_u to_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_field_I_want_change,因此顺序是clean_field>;clean@MyInlineFormSet 迪亚戈1.11

我相信通过迭代每个表单并设置清理后的数据(您的第二个示例),您的思路是正确的。BaseFormSet有一个名为cleaned_data的属性,它返回每个窗体的已清理数据的列表。这就是你想要的吗?E、 g.:

return self.cleaned_data

它实际上返回:

^{pr2}$

如果我正确地读取代码,它应该有正确的数据(修改后)。在

如果您只对在模型中保存值感兴趣,我建议您避免使用clean方法,而是重写save方法:

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

def save_existing(...)

相关问题 更多 >

    热门问题