如何在Django中创建电子邮件注册表格和电子邮件登录系统

时间:2019-08-12 18:45:05

标签: python django

我想用django创建一个具有password1和password2(确认密码)的电子邮件注册系统,以及一个电子邮件登录系统。我看到了几种解决方案,但对我没有用。任何帮助将不胜感激。

accounts / forms.py

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms


class UserCreateForm(UserCreationForm):
    class Meta:
        fields = ("email", "password1", "password2")
        model = User

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if User.objects.filter(email__iexact=email).exists():
            raise forms.ValidationError('A user has already registered using this email')
        return email

accounts / backends.py

class EmailBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        usermodel = get_user_model()
        try:
            user = usermodel.objects.get(email=username)
        except usermodel.DoesNotExist:
            return None
        else:
            if user.check_password(password):
                return user
        return None

settings.py

AUTHENTICATION_BACKENDS = ['accounts.backends.EmailBackend']

每当我尝试注册第二个用户时,都会出现以下错误:

UNIQUE constraint failed: auth_user.username

0 个答案:

没有答案