Python Django,如何使用用户名(uname) 或电子邮件作为登录凭据?

Python Django, How I Can use username(uname) or email as a login credentials?

Python Django,如何使用用户名(uname) 或电子邮件作为登录凭据? 我的 python 文件是视图、URL、模型,settings.py

def 登录页面(请求):

if request.method=="POST":
    try:
        Userdetails=newacc.objects.get(email=request.POST['email'],pwd=request.POST['pwd'])
        print("Username=",Userdetails)
        request.session[ 'email']=Userdetails.email
        return render(request,'Logout.html')
    except newacc.DoseNotExist as e:
        messages.success(request,' Username / Password Invalid.')
return render(request,'Login.html')

您可以使用 Q 对象在 emailuname 之间进行分离:

from django.db.models import <strong>Q</strong>

if request.method=="POST":
    try:
        Userdetails=newacc.objects.get(
            <strong>Q(email=request.POST['email']) | Q(uname=request.POST['email'])</strong>,
            pwd=request.POST['pwd']
        )
        print("Username=",Userdetails)
        request.session[ 'email']=Userdetails.email
        return render(request,'Logout.html')
    except newacc.DoseNotExist as e:
        messages.success(request,' Username / Password Invalid.')
return render(request,'Login.html')

但您的用户模型似乎没有使用密码散列。我强烈建议read the documentation on password management and hash passwords in your user model to prevent hackers from exploiting the passwords stored in the database if they manage to read that. See also this section on Customizing Authentication in Django