【问题标题】:Alter fields in Django formset using clean使用 clean 更改 Django formset 中的字段
【发布时间】:2014-05-09 10:28:59
【问题描述】:

如何使用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

这是行不通的,我看到人们迭代每个表单,但他们只验证而不改变。如果我遍历每个表单,我该如何返回cleaned_data?换句话说:

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
        ...?

【问题讨论】:

    标签: python django forms inline-formset formsets


    【解决方案1】:

    根据 ssomnoremac 评论,我在 BaseModelFormSet clean 方法中使用了 form.instance.field_i_wanted_to_change 而不是 form.cleaned_data['field_i_wanted_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_wanted_to_change,所以顺序是 clean_field > clean @MyInlineFormSet Django 1.11

    【讨论】:

      【解决方案2】:

      我相信通过遍历每个表单并设置清理数据(您的第二个示例),您走在了正确的轨道上。 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(...)
      

      【讨论】:

      • 大卫,谢谢。您对 self.cleaned_data 的回答是正确的,但这仍然没有改变该领域。问题是cleaned_data 只是访问器而不是修饰符。我需要的是:'form.instance.is_correct = True' form.instance 实际上修改了文档 [docs.djangoproject.com/en/dev/topics/forms/modelforms/… 中解释的字段
      • 添加到我的答案中。很高兴您能弄清楚,我认为这是一个有用的问题,因为内联表单的处理方式与普通表单有所不同。如果我没有说出您想要的答案,请随时提交您自己的答案。
      猜你喜欢
      • 2020-03-29
      • 1970-01-01
      • 2012-03-11
      • 2012-07-04
      • 1970-01-01
      • 2013-01-04
      • 2023-04-02
      • 2015-02-11
      • 1970-01-01
      相关资源
      最近更新 更多