python - Django Auth.authentication 始终为电子邮件返回 none
问题描述
我正在尝试实现注册和登录功能。
这是我的views.py
:
在 auth.authenticate 中
def login(request):
if request.method == 'POST':
f = auth.authenticate(email = request.POST['email'], password = request.POST['password'])
print(f)
if f is not None:
auth.login(request,f)
return redirect('home')
else:
return render(request,'login.html',{'error':'Wrong Username or password'})
else:
return render(request, 'login.html')
它总是返回None
,如果我更改为用户并尝试使用用户名和密码登录,那么它工作正常,它不适用于电子邮件和密码。IE
f = auth.authenticate(username= request.POST['username'], password = request.POST['password'])
我试过request.get.POST('email')
但没有工作,我也检查request.POST['email']
并request.POST['password']
包含有效信息。
解决方案
Django uses username field by default for authentication. If you want to use another field for authentication, you should extend the AbstractBaseUser and set email as the authentication field.
for settings.py:
AUTH_USER_MODEL = 'appname.User'
in your models.py:
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import BaseUserManager
class MyUserManager(BaseUserManager):
def create_user(self, email, password=None):
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, password):
user = self.create_user(email,
password=password,
)
user.admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(max_length=100, unique=True)
#other fields..
objects = MyUserManager()
USERNAME_FIELD = 'email'
Also you can see another approach in Django - Login with Email
推荐阅读
- pandas - 可视化目标中特定类的相关性
- java - 在 JavaMail IMAP 或 GIMAP 中归档邮件
- json - Spring - 返回原始 JSON 而不进行双重序列化
- reactjs - 什么是 AppBar 与 ToolBar?
- c# - 我可以在 C# 控制台应用程序中打印击键或鼠标单击的完整路径吗
- django - 访问 django 表单字段的子集
- c# - 如何实现 Entity Framework Core 数据过滤器?
- java - 基于我调用 get() 方法的方式的不同输出
- ios - 在检查无效字符时获取 UILabel 的文本以更改
- java - 通过同一个activity中的activity解析不同的数据