Django提示You have multiple authentication backends configured and therefore must provide the `backend

您配置了多个身份验证后端,因此必须为用户提供“backend”参数或设置“backend”属性。

setting.py 配置用户认证

AUTHENTICATION_BACKENDS = (
    # Django默认default
    'django.contrib.auth.backends.ModelBackend',
    'guardian.backends.ObjectPermissionBackend',
    # 微信登录验证
    'social_core.backends.weixin.WeixinOAuth2',
    # 微博登录验证
    # 'social.backends.weibo.WeiboOAuth2',
    # QQ登录验证
    # 'social.backends.qq.QQOAuth2',
)

我的场景是处理验证码登录报错

You have multiple authentication backends configured and therefore must provide the backend argument or set the backend attribute on the user.

class PhoneCode(APIView):
    """
    作者:阳光男孩 2020/11/13
    功能:用户手机号验证码登录
    """
    # 不作认证和授权
    authentication_classes = []
    permission_classes = []

    def post(self, request, *args, **kwargs):
        form = PhoneCodeForm(request.POST)
        print(request.POST)
        if form.is_valid():
            phone = form.cleaned_data['phone']
            code = form.cleaned_data['code']
            # 建立一个验证verify_obj,查询是否存在
            verify_obj = VerificationCode.objects.complex_filter(
                {
    
    "phone": phone, "code": code, "expire_date__gte": timezone.now()})
            # 如果验证object存在,验证码有效,查询或创建用户,返回token.
            if verify_obj.exists():
                user, user_create = C_User.objects.get_or_create(phone=phone)
                ########################################################################
				#login(request,user) 报错位置
                login(request, user, backend='django.contrib.auth.backends.ModelBackend')
                ########################################################################
                return redirect("names:names_list")
            else:
                context = {
    
    'code': 'status.HTTP_400_BAD_REQUEST', 'data': '', 'info': '您输入的验证码有误或已过期 请重新输入'}
                return render(request, "index/phone_code.html", context)
        else:
            error_message = ''
            for error in form.errors:
                error_message += '{0},'.format(error)
                error_message += '{0},'.format(error)

            return JSONResponse(code=status.HTTP_400_BAD_REQUEST, data={
    
    }, info="参数有误:{0}".format(error_message))

    def get(self, request):
        return render(request, "index/phone_code.html")

处理方案:

login(request, user, backend='django.contrib.auth.backends.ModelBackend')

猜你喜欢

转载自blog.csdn.net/weixin_44053341/article/details/109671247