django authentication in signup page error : 'local variable 'user' referenced before assignment

django authentication in signup page error : 'local variable 'user' referenced before assignment


这是我的注册身份验证 views.py def ,当我添加用户名和密码并点击注册时,它说这个错误:

local variable 'user' referenced before assignment

views.py定义:

def signup(request):

   if request.method == 'POST':
       if request.POST['password1'] == request.POST['password2']:
          try:
             user = User.objects.get(username = request.POST['username'])
             return render(request, 'accounts/signup.html', {'error':'try another 
             username'})
          except User.DoesNotExist:
             User.objects.create_user(request.POST['username'], password = 
             request.POST['password1'])
             auth.login(request,user)
             return redirect('home')
   else:
       return render(request, 'accounts/signup.html', {'error':'password error'})

您没有在 except 块中定义 user

User.objects.create_user(request.POST['username'], password = 
             request.POST['password1'])

应该是:

 user = User.objects.create_user(request.POST['username'], password = 
             request.POST['password1'])