在Django表单中,如何将“添加”错误添加到队列中?

时间:2010-12-13 23:40:31

标签: python django validation forms

def clean(self):
        cleaned_data = self.cleaned_data
        current_pass = cleaned_data['current_pass']
        new_pass = cleaned_data['new_pass']
        new_pass2 = cleaned_data['new_pass2']
        if current_pass or new_pass or new_pass2:
            if not current_pass:
                raise forms.ValidationError("- You must enter your current password.")
            if not new_pass:
                raise forms.ValidationError("- You must enter a new password.")
            if not new_pass2:
                raise forms.ValidationError("- You must re-confirm your new password.")
        return cleaned_data

现在,我提出错误。但这意味着其他错误不会弹出。当我举起第一个时它结束了这个功能。如果我想要全部3个错误怎么办?

3 个答案:

答案 0 :(得分:3)

解决方案可能是将这些错误绑定到相关字段,如in the docs所述。

您的代码如下所示:

def clean(self):
    cleaned_data = self.cleaned_data
    current_pass = cleaned_data['current_pass']
    new_pass = cleaned_data['new_pass']
    new_pass2 = cleaned_data['new_pass2']
    if current_pass or new_pass or new_pass2:
        if not current_pass:
            self._errors["current_pass"] = self.error_class(["- You must enter your current password."])
        if not new_pass:
            self._errors["new_pass"] = self.error_class(["- You must enter a new password."])
        if not new_pass2:
            self._errors["new_pass2"] = self.error_class(["- You must re-confirm your new password."])
        del cleaned_data["current_pass"]
        del cleaned_data["new_pass"]
        del cleaned_data["new_pass2"]
    return cleaned_data

请注意我无法亲自测试。

答案 1 :(得分:1)

通过使用clean方法,您正在进行每个表单验证。整个表单的验证器失败了。

对于单个字段,您应该使用clean_fieldname方法而不是clean方法,这些方法在单个字段验证后运行。

如果您使用clean_fieldname,则可以访问forminstance.errorsforminstance.field.errors

中的错误
def clean_current_pass(self):
    data = self.cleaned_data.get('current_pass'):
    if not data:
        raise forms.ValidationError('- You must enter your current password.')
    return data

def clean_new_pass(self):
    data = self.cleaned_data.get('new_pass'):
    if not data:
        raise forms.ValidationError("- You must enter a new password.")
    return data

def clean_new_pass2(self):
    data = self.cleaned_data.get('new_pass2'):
    if not data:
        raise forms.ValidationError('- You must re-confirm your new password.')
    return data

{{myform.errors}}会在模板中显示所有错误。

答案 2 :(得分:0)

(这是一个Python问题而不是Django问题。)

这应该是这样的:当引发错误时,它应该立即向上传播直到它被处理。你不能指望评估函数的其余部分,因为还没有处理错误!

可能最简单,最干净的方法是重写代码:

check = (current_pass, new_pass, new_pass2)
code = ("You must enter your current password.", ...)
err = ''.join(code for i, code in enumerate(codes) if check[i])
if err:
    raise forms.ValidationError(err)