gpt4 book ai didi

python - 无法在 django 中使用电子邮件登录

转载 作者:太空宇宙 更新时间:2023-11-03 21:48:01 26 4
gpt4 key购买 nike

我尝试使用电子邮件而不是 django 中的用户名登录,但它不起作用。我也没有收到任何错误。

我还在 stackoverflow 和其他博客/帖子中查找了解决方案,但没有得到输出。

您能否检查一下我的代码,其中有错误/需要修改。欢迎任何建议或更改。

这是我的代码:

models.py

from django.db import models
from django.contrib.auth.models import (BaseUserManager,AbstractBaseUser)

# Create your models here.

class UserManager(BaseUserManager):
def create_user(self, email,password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')

user = self.model(
email=self.normalize_email(email),
)

user.set_password(password)
user.save(using=self._db)
return user

def create_superuser(self, email, date_of_birth, password):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(
email,
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user


class MyUser(AbstractBaseUser):
email = models.EmailField(verbose_name='email address',
max_length=255,
unique=True,
)

is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)

objects = UserManager()

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []

def __str__(self):
return self.email

def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True

def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True

@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin

views.py

from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model,authenticate

from .forms import RegisterForm,LoginForm
# Create your views here.
def home(request):
return render(request,'home.html',{})


def register_view(request):
form = RegisterForm(request.POST or None)
context = {"form":form}

if form.is_valid():
email = form.cleaned_data['email']
password = form.cleaned_data['password']

new_user = User.objects.create_user(email,password)

return render(request,'register.html',context)

def login_view(request):
form = LoginForm(request.POST or None)
context = {"form" : form}
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(request,username = username,password=password)
if user is not None:
login(request, user)
print("Looged In")
return redirect('home')

else:
print("Username or Password is Wrong")

return render(request,'login.html',context)

backends.py

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend

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 = ['profile_manager.backends.EmailBackend']
AUTH_USER_MODEL = 'profile_manager.MyUser'

forms.py

from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
from .models import MyUser


User = get_user_model()
class RegisterForm(forms.Form):


email =forms.EmailField(widget = forms.TextInput(
attrs = {"class":"form-control",
"placeholder":"Email"
}),label='')

password = forms.CharField(widget =forms.PasswordInput(attrs = {"class":"form-control",
"placeholder":"Password"
}),label='')

password2 = forms.CharField(label ='' , widget = forms.PasswordInput(attrs = {"class":"form-control",
"placeholder":"Confirm Password"
}))



def clean_email(self):
email = self.cleaned_data.get('email')
qs = User.objects.filter(email =email)
if qs.exists():
raise forms.ValidationError("Email is already taken")
return email

def clean(self):
data =self.cleaned_data
password = self.cleaned_data.get('password')
password2 = self.cleaned_data.get('password2')
if password2!= password:
raise forms.ValidationError("Password must match")
return data


class LoginForm(forms.Form):

email = forms.EmailField(widget = forms.TextInput(
attrs = {"class":"form-control",
"placeholder":"Username"
}),label='')

password = forms.CharField(widget =forms.PasswordInput(attrs = {"class":"form-control",
"placeholder":"Password"
}),label='')

最佳答案

您的 login_view 中的这一行不可能是正确的:

username = form.cleaned_data.get("username")

您的表单没有用户名字段,只有电子邮件字段。

关于python - 无法在 django 中使用电子邮件登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52333867/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com