【问题标题】:How to check if one field matches another in Django Form如何检查一个字段是否与Django Form中的另一个字段匹配
【发布时间】:2026-01-03 13:30:01
【问题描述】:

我正在尝试让我的表单检查电子邮件字段是否与我的 Django 表单中的 verify_email 字段匹配,但它不起作用。

我的 forms.py 文件:

class SignupForm(ModelForm):
    class Meta:
        model = FormSubmission
        fields ='__all__'
        widgets = {'botcatcher': forms.HiddenInput()}

        def clean(self):
            cleaned_data = super().clean()
            email = self.cleaned_data.get('email')
            vmail = self.cleaned_data.get('verify_email')

            if email != vmail:
                raise forms.ValidationError(_("Emails must 
                match"), code="invalid")
            return cleaned_data

我的 model.py 文件:

class FormSubmission(models.Model):
    first_name = models.CharField(max_length = 30)
    last_name = models.CharField(max_length = 30)
    email = models.EmailField(unique= False)
    verify_email = models.EmailField(unique = False)
    text = models.CharField(max_length=250)
    botcatcher = models.CharField(max_length= 1, blank=True, 
    validators=[validators.MaxLengthValidator(0)])


    def __str__(self):
        return "%s %s"% (self.first_name, self.last_name)

【问题讨论】:

    标签: django django-models django-forms data-cleaning modelform


    【解决方案1】:

    这是我对 def clean 函数的缩进。

    【讨论】:

      最近更新 更多