简体   繁体   English

在 Django 中分配之前引用 /signin/ 局部变量“用户”处的 UnboundLocalError

[英]UnboundLocalError at /signin/ local variable 'user' referenced before assignment in Django

Function to let the user to login as follows=>让用户登录的功能如下=>


Obviously this error pops:显然这个错误弹出:

def login_view(request):
  if request.method == 'POST':

    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password =password  )
  if user is not None:
    login(request, user)
    return HttpResponseRedirect(reverse("index"))
  elif user is None:
                      return render(request, "covi/signin.html", {
            "message": "Invalid username and/or password."
        })
  else:
                      return render(request, "covi/signin.html")                  
            
           

It's because user = authenticate(request, username=username, password =password) runs only if request.method == 'POST' .这是因为user = authenticate(request, username=username, password =password)仅在request.method == 'POST'时运行。 If you do a GET request user won't be assigned.如果您执行 GET 请求,则不会分配用户。

def login_view(request):
  if request.method == 'POST':

    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password =password  )
    if user is not None:
      login(request, user)
      return HttpResponseRedirect(reverse("index"))
    elif user is None:
      return render(request, "covi/signin.html", {
            "message": "Invalid username and/or password."
      })
  return render(request, "covi/signin.html")   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 分配前在/本地变量'user'处引用了UnboundLocalError - UnboundLocalError at / local variable 'user' referenced before assignment UnboundLocalError:分配前已引用本地变量“用户” - UnboundLocalError: Local variable 'user' referenced before assignment UnboundLocalError:分配前已引用局部变量“ r”(Django) - UnboundLocalError: local variable 'r' referenced before assignment (Django) UnboundLocalError:在Django中赋值之前引用了局部变量“ form” - UnboundLocalError: local variable 'form' referenced before assignment in Django UnboundLocalError-分配前引用的局部变量-Django - UnboundLocalError- local variable referenced before assignment - Django UnboundLocalError:在 DJANGO 中赋值之前引用了局部变量“formset” - UnboundLocalError: local variable 'formset' referenced before assignment in DJANGO Django UnboundLocalError:分配前引用的局部变量“标签” - Django UnboundLocalError: local variable 'tags' referenced before assignment Django - UnboundLocalError:分配前引用的局部变量“image_link” - Django - UnboundLocalError: local variable 'image_link' referenced before assignment UnboundLocalError:分配前已引用局部变量“ truebomb” - UnboundLocalError: local variable 'truebomb' referenced before assignment UnboundLocalError:分配前已引用局部变量“ cur” - UnboundLocalError: local variable 'cur' referenced before assignment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM