簡體   English   中英

django自定義表單clean()從clean_field()引發錯誤

[英]django custom form clean() raising error from clean_field()

我已經創建了一個自定義表單,並且需要覆蓋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()方法中再次引發由clean_xxxx()引發的錯誤呢?

在您的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方法中看到錯誤,因此您無需創建另一個錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM