用户身份验证无法正常工作Django

时间:2018-07-17 12:24:39

标签: python django authentication django-models django-users

我尝试登录时用户未获得身份验证。

这是我的注册码

def register(request):
if request.method == "POST":
    username = request.POST["name"]
    email =  request.POST["email"]
    password = request.POST["password"]
    password2 = request.POST["password2"]

    try:
        if password2 != password:
            messages.error(request, "password did'nt match")
        elif User.objects.get(email=email):
            messages.error(request, "user already exists")
    except: 
        if email and username:
            user = User.objects.create_user(username=username, email=email)
            user.set_password(password)
            user.save()
            messages.success(request, "user created")
        else:
            messages.error(request, "Looks like user already exists")

return render(request, 'register.html', {})

这是我的登录代码(如果我使用user.object.get作为电子邮件,而check_password作为密码)则正常工作,但是当我使用身份验证时,却无法正常工作。打印身份验证返回无

def login(request):

    if request.method == "POST":
        email = request.POST["email"]
        password = request.POST["password"]
        print email
        print password
        try:
            user = authenticate(email=email , password=password)
            if user is not None:
                login(request, user)                    
                return redirect('dashbord')
            else:
                messages.error(request, "password yesn't match")

        except:

            messages.error(request, "login fail plz check ur password or email again")


    return render(request, 'login.html', {})

1 个答案:

答案 0 :(得分:0)

根据您的评论,您使用的是默认身份验证系统,但您可以通过以下行进行身份验证:

user = authenticate(email=email , password=password)

根据您的问题,解决方法是:
    email = request.POST["email"]

username = request.POST["name"]
user = authenticate(username=username , password=password)

默认情况下,使用用户名而不是电子邮件(cf:the documentation)的django日志。

对于您在评论中的问题,它与Django - Login with Email相同。 我邀请您在接受的答案中找到解决方案。