【问题标题】:Django TypeError: authenticate() takes exactly 0 arguments (3 given)Django TypeError: authenticate() 只需要 0 个参数(给定 3 个)
【发布时间】:2018-02-06 05:41:38
【问题描述】:

Django version 1.10.7

我收到TypeError: authenticate() takes exactly 0 arguments (3 given)

像这样导入 authenticate():
from django.contrib.auth import authenticate, login

像这样调用 authenticate() :
authenticate(request, username=request.POST['username'] ,password=request.POST['password'])

【问题讨论】:

    标签: python django django-1.10


    【解决方案1】:

    在 1.10 中 authenticate 不接受位置参数 (docs) 称之为

    authenticate(username=request.POST['username'], password=request.POST['password'])
    

    【讨论】:

    • docs.djangoproject.com/en/1.11/topics/auth/default/… :在给定的示例中,身份验证的使用类似于user = authenticate(request, username=username, password=password)
    • @batMan 没错,但要注意版本。在 1.11 中,Django 添加了一个可选的请求参数,但 1.10 没有。
    • 好的 所以这仅在 1.11 中是可选的。说得通。我刚试过,它奏效了。希望我能在这里接受所有 3 个答案。无论如何,我对所有这些都投了赞成票。感谢您的快速回答。
    【解决方案2】:

    将authenticate设置为变量,不传入request,如:

    auth = authenticate(username=request.POST['username'] ,password=request.POST['password'])
    

    然后使用 login 让用户登录:

    login(request, auth)
    

    别忘了导入登录名

    【讨论】:

    • docs.djangoproject.com/en/1.11/topics/auth/default/… :在给定的示例中,身份验证的使用类似于user = authenticate(request, username=username, password=password)
    • 希望我能在这里接受所有 3 个答案。无论如何,我对所有这些都投了赞成票。感谢您的快速回答。
    【解决方案3】:

    在没有请求的情况下使用身份验证,只需要用户名和密码authenticate(username=XXX,password=XXX)。参见文档https://docs.djangoproject.com/en/1.11/_modules/django/contrib/auth/#authenticate

    【讨论】:

    • docs.djangoproject.com/en/1.11/topics/auth/default/… :在给定的示例中,身份验证的使用类似于user = authenticate(request, username=username, password=password)
    • 您使用的是 Django 1.10.7 版本,该选项是在 1.11 版本中添加的。阅读笔记。
    • 希望我能在这里接受所有 3 个答案。无论如何,我对所有这些都投了赞成票。感谢您的快速回答。
    猜你喜欢
    • 2016-07-22
    • 2016-08-17
    • 2012-10-19
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    相关资源
    最近更新 更多