且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django 1.9检查电子邮件是否已经存在

更新时间:2023-11-29 15:47:40

您可以覆盖UserForm上的clean_<INSERT_FIELD_HERE>()方法来检查这种特殊情况.看起来像这样:

You can override the clean_<INSERT_FIELD_HERE>() method on the UserForm to check against this particular case. It'd look something like this:

forms.py:

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('email',)

    def clean_email(self):
        # Get the email
        email = self.cleaned_data.get('email')

        # Check to see if any users already exist with this email as a username.
        try:
            match = User.objects.get(email=email)
        except User.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 UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('first_name', 'last_name', 'company', 'website', 'phone_number')

您可以在有关表单的Django文档.

也就是说,我认为您应该考虑创建一个自定义用户模型,而不是将您的User Profile类视为User的包装.

That said, I think you should look into creating a custom user model instead of treating your User Profile class as a wrapper for User.