Search code examples
djangodjango-viewsdjango-authentication

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



this is my signup authentication views.py def , when i add username and password and hit signup it says this error :

local variable 'user' referenced before assignment

views.py def :

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'})

Solution

  • You don't define user in the except block.

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

    Should be:

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