Django 自定义用户注册中的电子邮件表单不匹配

Email forms do not match in Django Custom-User registration

我正在设置一个自定义用户注册表,以便在我的 Django 项目上创建一个帐户。我觉得我错过了一些非常简单的东西,使我出于某种原因无法注册。 我的注册表要求在新用户注册之前填写 4 个字段。在这 4 个字段中,有两个只是对电子邮件地址的确认。

这是我的副本 form.py:

class UserRegisterForm(forms.ModelForm):
    username = forms.CharField(label='Username')
    email = forms.EmailField(label='Email Address')
    email2 = forms.EmailField(label='Confirm Email')
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = CustomUser
        fields = ['username', 'email', 'email2', 'password']

    def clean_email(self):
        email = self.cleaned_data.get('email')
        email2 = self.cleaned_data.get('email2')
        if email != email2:
            raise forms.ValidationError("Emails do not match")

这是我的副本 view.py:

def register_view(request):
    next = request.GET.get('next')
    form = UserRegisterForm(request.POST or None)
    if form.is_valid():
        user = form.save(commit=False)
        password = form.cleaned_data.get('password')
        user.set_password(password)
        user.save()
        new_user = authenticate(username=user.username, password=password)
        login(request, new_user)
        if next:
            return redirect(next)
        return redirect('/home/')
    context = {'form':form, "title":"register"}
    return render(request, "register.html", context)

这是我的 html 文件:

<h2><center><font color="white">Register Here:</font></center></h2>
    <form method="POST"><center>
        {% csrf_token %}
        {{form}}
      <input type="submit" />
    </center></form>

每当我尝试注册为新用户时,都会出现我的表单验证错误,因为我说我的两个电子邮件不匹配(我复制粘贴它们以确保它们相同)。

我觉得我错过了一些就在我眼皮底下的东西...

为大家干杯,非常感谢。

试试这个

def register_view(request):
    next = request.GET.get('next')
    form = UserRegisterForm(request.POST or None)
    if form.is_valid():
       email = form.cleaned_data.get('email')
       email1 = form.cleaned_data.get('email1')
        if email1 == email 
           user = form.save(commit=False)
           password = form.cleaned_data.get('password')
           user.set_password(password)
           user.save()
           new_user = authenticate(username=user.username, password=password)
           login(request, new_user)
              if next:
                 return redirect(next)
          else:
             ….

    def clean(self):
        cleaned_data = super(UserRegisterForm, self).clean()
        email = cleaned_data.get('email')
        email2 = cleaned_data.get('email2')
        if email != email2:
            self.add_error("email", "Emails do not match")

问题是在 clean_email 方法中,您 email2 总是 None。要比较两个或多个字段,请使用 clean 方法