首页 > 解决方案 > 模型表单中的 Django 电子邮件验证错误(注册)

问题描述

如果使用该电子邮件的用户已经存在,我正在尝试验证注册表单的电子邮件,它应该显示一个错误,例如电子邮件已经存在,但我无法使用以下代码实现这一点

表格.py

from django.forms import ModelForm
from django import forms
from . models import signup

class signupForm(ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    confirm_password = forms.CharField(widget=forms.PasswordInput)
    class Meta:
        model = signup
        fields = ['username', 'email' , 'password','confirm_password']
    def clean(self):
        cleaned_data = super(signupForm, self).clean()
        password = cleaned_data.get("password")
        confirm_password = cleaned_data.get("confirm_password")


        if password != confirm_password:
            raise forms.ValidationError(
                "password and confirm_password does not match"
            )    
        email = self.cleaned_data.get('email')
        try:
            match = signup.objects.get(email=email)
            print(match)
        except signup.DoesNotExist:
            # Unable to find a user, this is fine
            return email

        # A user was found with this as a username, raise an error.
        raise forms.ValidationError('This email address is already in use.')
class loginForm(ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    class Meta:
        model = signup
        fields = ['email','password']

它在 /signup 'str' 对象处显示 AttributeError 没有属性 'get' 这个错误

标签: django

解决方案


如果没有匹配项,您将从 clean 方法返回电子邮件字符串。但是主要clean方法应该返回整个cleaned_data dict,而不是单个字段。

但无论如何,验证逻辑的那部分应该放在特定clean_email方法中,该方法确实需要返回电子邮件字符串。所以你会有:

def clean_email(self):
    email = self.cleaned_data.get('email')
    try:
        match = signup.objects.get(email=email)
        print(match)
    except signup.DoesNotExist:
        # Unable to find a user, this is fine
        return email

    # A user was found with this as a username, raise an error.
    raise forms.ValidationError('This email address is already in use.')

def clean(self):
    cleaned_data = super(signupForm, self).clean()
    password = cleaned_data.get("password")
    confirm_password = cleaned_data.get("confirm_password")


    if password != confirm_password:
        raise forms.ValidationError(
            "password and confirm_password does not match"
        )
    return cleaned_data

(请注意,与此问题无关,但您的登录表单不应是 ModelForm;这将导致其他验证问题。)


推荐阅读