【问题标题】:django custom form clean() raising error from clean_field()django 自定义表单 clean() 从 clean_field() 引发错误
【发布时间】:2016-09-26 15:35:56
【问题描述】:

我创建了一个自定义表单,需要同时覆盖clean_field() 方法和clean() 方法。这是我的代码:

class MyForm(forms.Form):
    username=forms.RegexField(regex=r'^1[34578]\d{9}$')
    code = forms.RegexField(regex=r'^\d{4}$')

    def clean_username(self):
        u = User.objects.filter(username=username)
        if u:
            raise forms.ValidationError('username already exist')
        return username

    def clean(self):
        cleaned_data = super(MyForm, self).clean()
        # How can I raise the field error here?

如果我保存此表单两次,并且第二次用户名已经存在,clean_username 方法会报错,但是clean() 方法仍然运行而不会中断。

所以我的问题是,当cleaned_xxx 已经引发错误时,我该如何停止调用clean(),如果这是不可能的,那么我该如何再次引发clean_xxxx()clean() 方法中引发的错误?

【问题讨论】:

    标签: python django forms validation


    【解决方案1】:

    在您的clean 方法中,您可以检查username 是否在cleaned_data 字典中。

    def clean(self):
        cleaned_data = super(MyForm, self).clean()
        if 'username' in cleaned_data:
            # username was valid, safe to continue
            ...
        else:
            # raise an exception if you really want to
    

    您可能不需要 else 语句。用户将从clean_username 方法中看到错误,因此您无需创建另一个。

    【讨论】:

    • 感谢您的宝贵时间,非常感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 2012-04-15
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    相关资源
    最近更新 更多