/ accounts/login /上的AttributeError'用户'对象没有属性'user'

Cor*_*ant 3 python authentication django

我是django的新手并试图让用户身份验证正常工作.我已经设置了一个非常基本的登录表单和视图,但我收到错误:

AttributeError at /accounts/login/ 'User' object has no attribute 'user'
Run Code Online (Sandbox Code Playgroud)

我很困惑,因为我没有尝试访问User.user
我知道它必须是第一个else语句中的东西,因为经过身份验证的用户只是重定向到"/",因为它应该
是视图:

def login(request):
  if request.user.is_authenticated():
    return HttpResponseRedirect("/")
  else:
    if request.method == 'POST':
      username = request.POST['username']
      password = request.POST['password']
      user = authenticate(username=username, password=password)
      if user is not None:
        if user.is_active:
          login(user)
          return HttpResponseRedirect("/")
      return HttpResponse("There was an error logging you in")
    else:
      return render_to_response("registration/login.html", 
                                 context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

在views.py第15行引发错误:if request.user.is_authenticated():

Dan*_*man 5

您的视图函数被调用login,它只需要一个参数request.

在你的观点的第11行,你打电话login(user).现在,您可能意味着要成为登录函数django.contrib.auth,并且可能是您从视图顶部导入它.但是Python一次只能使用一个名称:所以当你命名你的视图时login,它会覆盖现有的对该名称的引用.

结果就是该行调用了您的视图,而不是登录功能.(这就是为什么你得到特定的错误:你的看法检查的第一线request.user,以request从通常是请求的第一个参数-但在你的情况,你已经通过user作为第一个参数,当然用户没有按" t本身有一个用户参数.)

解决方案是将视图重命名为其他内容,或者在视图中from django.contrib import auth调用auth.login(user).