的形式。cleaned_data是在表单处理过程中使用的。

时间:2022-02-18 16:23:40

It's a really simple form but I don't know where's got wrong. When I check the debug mode of django site, I found that the clean_data of new field is missing, as the picture of following:

这是一个很简单的形式,但我不知道哪里出错了。当我检查django站点的调试模式时,我发现新字段的clean_data丢失了,如下图所示:

的形式。cleaned_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']

1 个解决方案

#1


1  

The problem is if you type same new and old password then clean_new method raise exception and return no value. That's why in clean_new_confirm which performed after clean_new cleaned_data is not contains new value.

问题是,如果您键入相同的新密码和旧密码,那么clean_new方法将引发异常,并且不返回任何值。这就是为什么在clean_new cleaned_data之后执行的确认中不包含新值。

You can avoid error just using get. Check first if cleaned_data contains new value and if yes, check if new equals to new_confirm:

您可以使用get避免错误。首先检查cleaned_data是否包含新值,如果包含,则检查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']

#1


1  

The problem is if you type same new and old password then clean_new method raise exception and return no value. That's why in clean_new_confirm which performed after clean_new cleaned_data is not contains new value.

问题是,如果您键入相同的新密码和旧密码,那么clean_new方法将引发异常,并且不返回任何值。这就是为什么在clean_new cleaned_data之后执行的确认中不包含新值。

You can avoid error just using get. Check first if cleaned_data contains new value and if yes, check if new equals to new_confirm:

您可以使用get避免错误。首先检查cleaned_data是否包含新值,如果包含,则检查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']