form.cleaned_data 正在处理表格

form.cleaned_data is while form handling

表格真的很简单,但我不知道哪里错了。当我检查django站点的调试模式时,我发现new字段的clean_data丢失了,如下图:

class PasswordEditForm(forms.Form):
  old = forms.CharField(widget=forms.PasswordInput, min_length=6,
                      max_length=30, label='舊密碼', label_suffix=' ')
  new = forms.CharField(widget=forms.PasswordInput, min_length=6,
                      max_length=30,  label='新密碼', label_suffix=' ')
  new_confirm = forms.CharField(widget=forms.PasswordInput, min_length=6,
                              max_length=30,  label='再輸入一次', label_suffix=' ')

  def clean_new(self):
    cd = self.cleaned_data
    if cd['old'] == cd['new']:
      raise forms.ValidationError('新密碼與舊密碼相同')
    return cd['new']

  def clean_new_confirm(self):
    cd = self.cleaned_data
    if cd['new'] != cd['new_confirm']:
      raise forms.ValidationError('兩次輸入密碼不相符')
    return cd['new_confirm']

问题是如果您键入相同的新旧密码,那么 clean_new 方法会引发异常并且 return 没有值。这就是为什么在 clean_new cleaned_data 之后执行的 clean_new_confirm 中不包含 new 值。

您只需使用 get 即可避免错误。首先检查 cleaned_data 是否包含 new 值,如果是,则检查 new 是否等于 new_confirm:

def clean_new_confirm(self):
    cd = self.cleaned_data
    new_pass = cd.get('new')
    if new_pass and new_pass != cd.get('new_confirm'):
        raise forms.ValidationError('兩次輸入密碼不相符')
    return cd['new_confirm']