gpt4 book ai didi

Django 如何在自定义表单的子类中覆盖 clean() 方法?

转载 作者:行者123 更新时间:2023-12-04 00:38:54 25 4
gpt4 key购买 nike

我创建了一个带有自定义验证的自定义表单,如下所示:

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() 方法的正确方法是什么?
目前,这就是我所做的:
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() 方法返回 cleaned_data在我看来这有点奇怪。
这是正确的方法吗?

最佳答案

你做得很好,但你应该像这样从 super 调用加载cleaned_data:

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() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16231183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com