【问题标题】:user authenticate is not working Django用户身份验证不起作用 Django
【发布时间】:2018-12-25 03:40:16
【问题描述】:

当我尝试登录时,用户未通过身份验证。

这是我的注册码

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 作为密码,它可以工作,但是当我使用身份验证时,它不工作。打印身份验证返回 None

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', {})

【问题讨论】:

  • 如果User 尚不存在,您的elif User.objects.get(email=email): 将引发错误。
  • 您是否将 Django 配置为通过电子邮件进行身份验证?该文档显示您应该使用 args 用户名和密码进行身份验证,而不是电子邮件和密码。 (编辑:docs.djangoproject.com/fr/2.0/topics/auth/default/… -> 默认为用户名和密码,如果在身份验证过程中引发“PermissionDenied”,则该函数返回的值为 None。)
  • 对。默认情况下,您只能使用用户名和密码登录。
  • 此评论与您的​​问题的解决方案无关,因为在上述 cmets 中已经有有效的尝试,但请检查您的错误消息中的语法 (did'nt,yesn't, plz),这是失控。
  • yes+not 的正确缩写是“y'ain't”,例如,“Oh hell naw, y'ain't put in the correct password.”

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


【解决方案1】:

根据您的评论,您使用的是默认身份验证系统,但您使用此行进行身份验证:

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

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

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

默认情况下,django 使用用户名登录,而不是使用电子邮件(参见:the documentation)。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-02
    • 2017-07-14
    • 2016-10-17
    • 2015-10-12
    • 2015-07-13
    • 2011-08-30
    • 2013-11-03
    • 2017-06-02
    相关资源
    最近更新 更多