Search code examples
djangodjango-authentication

User is always none, doesn't allow the user to sign in


While creating a login and signup form, I have been having issues with the sign up form, the issue is that whenever I create user through registration and try to log in with the test user it doesn't log, always points the Httpresponse I have set up. After checking the admin panel the user is being created, now I do not know where to go, I do think I am not grabbing the right data or its not grabbing it


## Register
def register(request):
    if request.method == 'GET':
        return render(request, 'auth/register.html', { })
    if request.method == 'POST':
        form = RegistrationForm(request.POST)

        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            passwordConf = form.cleaned_data['passwordConf']
            email = form.cleaned_data['email']
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']

            user = User.objects.create_user(username, password, email)

            if password == passwordConf:
                return HttpResponseRedirect("/auth/signin")
            else:
                return HttpResponse("Passwords do not match", status=400)   
        else:
            return HttpResponse("Invalid registration request.(Bad Request)", status=400)

    else:
        form = RegistrationForm      
        return HttpResponse("Method not allowed on /auth/register.(Method Not Allowed)", status=405)


## Signin
def signin(request):
    if request.method == 'GET':
        return render(request, 'auth/signin.html', { })

    if request.method == 'POST':
        form = SigninForm(request.POST)

        if form.is_valid():
            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('/')
            else:
                return HttpResponse('Invalid Credientials', status=401 )
        else:
            return HttpResponse("Form is not valid", status=401)

Solution

  • Your create_user is sending a different order of arguments than expected. According to docs, it has the signature create_user(username, email=None, password=None, **extra_fields).

    Currently, by using user = User.objects.create_user(username, password, email), you are setting user.email=password and user.password=email.

    You need to use:

    user = User.objects.create_user(username, email, password)