Django如何在自定义窗体的子类中覆盖clean()方法? [英] Django how to override clean() method in a subclass of custom form?

查看:119
本文介绍了Django如何在自定义窗体的子类中覆盖clean()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个带有自定义验证的自定义表单:

I created a custom form with custom validation like this:

class MyCustomForm(forms.Form):
    # ... form fields here

    def clean(self):
        cleaned_data = self.cleaned_data
        # ... do some cross-fields validation here

        return cleaned_data

现在,这个窗体是用另一个具有自己的clean方法的表单进行子类化的。

什么是正确的方法来触发clean()方法?

此刻,这就是我所做的:

Now, this form is subclassed with another form which has its own clean method.
What is the correct way to trigger both clean() methods?
At the moment, this is what I do:

class SubClassForm(MyCustomForm):
    # ... additional form fields here

    def clean(self):
        cleaned_data = self.cleaned_data
        # ... do some cross-fields validation for the subclass here

        # Then call the clean() method of the super  class
        super(SubClassForm, self).clean()

        # Finally, return the cleaned_data
        return cleaned_data

似乎有效。但是,这使得两个clean()方法返回 clean_data ,这对我来说似乎有点奇怪。

这是正确的吗?

It seems to work. However, this makes two clean() methods return cleaned_data which seems to me a bit odd.
Is this the correct way?

推荐答案

你做得很好,但是你应该加载clean_data从超级调用,如下所示:

You do it well, but you should load cleaned_data from super call like this:

class SubClassForm(MyCustomForm):
# ... additional form fields here

def clean(self):
    # Then call the clean() method of the super  class
    cleaned_data = super(SubClassForm, self).clean()
    # ... do some cross-fields validation for the subclass 

    # Finally, return the cleaned_data
    return cleaned_data

这篇关于Django如何在自定义窗体的子类中覆盖clean()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆