Невозможно войти в систему с помощью электронной почты в django
Я создал пользовательскую модель пользователя, но не могу войти в систему с действительным email id и паролем
models.py
class User(AbstractBaseUser):
email = models.EmailField(verbose_name='email address',
max_length=255,
unique=True,
)
is_active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False) # a superuser
objects = UserManager()
# notice the absence of a "Password field", that is built in.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
написаны такие методы, как has_perm, has_module_perm.
forms.py
class AuthenticationForm(forms.Form):
email = forms.EmailField(widget=forms.TextInput(
attrs={'class': 'form-control','type':'text','name': 'email','placeholder':'Email'}),
label='Email')
password = forms.CharField(widget=forms.PasswordInput(
attrs={'class':'form-control','type':'password', 'name': 'password','placeholder':'Password'}),
label='Password')
class Meta:
fields = ['email', 'password']
views.py
def loginEmployeeView(request):
if request.method == 'POST':
form = AuthenticationForm(data = request.POST)
if form.is_valid():
print("1")
email = request.POST.get('email')
password = request.POST.get('password')
print("2")
user = authenticate(email=email, password=password)
print("3")
if user is not None:
if user.is_active:
print("4")
login(request,user)
messages.success(request,'Logged in successfully')
return redirect('dashboard')
else:
messages.error(request,'user is not active')
return redirect('login-employee')
else:
messages.error(request,'invalid username or password')
return redirect('login-employee')
else:
print("5")
form = AuthenticationForm()
return render(request,'accounts/login.html',{'form':form,})
Я пытался войти в систему с действительной информацией, но все равно показывает, что имя пользователя или пароль недействительны. Спасибо.
Вам следует использовать другой бэкенд аутентификации, который проверяет учетные данные с заданным объектом пользователя. Такой бэкенд может выглядеть следующим образом:
# app_name/backend.py
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
UserModel = get_user_model()
class EmailBackend(ModelBackend):
def authenticate(self, request, email=None, password=None):
try:
user = UserModel.objects.get(email=email)
except UserModel.DoesNotExist:
UserModel().set_password(password)
return None
if user is not None and user.check_password(password):
if user.is_active:
return user
return None
Затем в файле настроек вы должны использовать EmailBackend
для настройки AUTHENTICATION_BACKENDS
[Django-doc]:
# settings.py
# ⋮
AUTHENTICATION_BACKENDS = [
'app_name.backends.EmailBackend'
]
# ⋮