2010-12-13 83 views
0
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个错误怎么办?在Django窗体中,如何将错误添加到队列中?

回答

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 

请小心,我不能测试它亲自虽然。

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) 
+0

所以,我应该把错误列表中,并提出名单? – TIMEX 2010-12-13 23:51:17

+0

不,您应该引发_one_错误,您应根据发生的故障创建错误。 – katrielalex 2010-12-14 01:46:19

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}}会给你所有的错误在你的模板。

相关问题