django模型形式用外键清理方法

时间:2016-01-11 15:47:15

标签: django django-forms

我尝试使用外键覆盖模型表单的清理方法。

型号:

 Doc(Model):
   name = CharField()
   doc_type = ForeignKey(DictDocType)

形式:

    class DocForm(ModelForm):

      class Meta:
        model = Doc
        fields = '__all__'

      def clean_doc_type(self)
        doc_type_name = self.cleaned_data['doc_type']

        try:
            DictDocType.objects.get(name=doc_type_name)
        except DictDocType.DoesNotExist:
            msg = '{0} does not exist in dictdoc {1}.'.format(
                doc_type_name, self.cleaned_data['name'])
            raise ValidationError(msg)
        return name

在测试中我收到错误:

  

KeyError:' name'。如果我从msg中移除self.cleaned_data [' name'] - 我   不要得到self.cleaned_data [' doc_type']。

我哪里错了?

1 个答案:

答案 0 :(得分:3)

您无法在clean_foo方法中交叉引用其他字段,因为当您在其中一个方法中时,并非所有字段都会调用clean_foo方法。可能还有一些尚未填充的表单值,因此在您调用clean_name()时尚未调用clean_doc_type(),因此您没有self.cleaned_data['name']

这应该在clean方法中完成。 Django doc非常明确地记录了这一点:

  

当调用表单的clean()方法时,所有个体   将运行字段清理方法(前两节),所以   self.cleaned_data将填充任何幸存下来的数据   远。所以你还需要记住允许的事实   您想要验证的字段可能无法在初始阶段幸存   个别实地考察。

此外,您的清洁方法没有多大意义,根本没有必要。您无法选择foreignkey中不存在的ModelForm。即使您强制前端执行此操作,该字段也会自动验证失败并给出错误:

  

选择有效的选择。 foo不是可用的选择之一。

相关问题