首页 > 解决方案 > 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']包含有效信息。

标签: pythondjango

解决方案


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


推荐阅读