[Django]-Django : authenticate() is not working for users created by register page, but working for those users who were created by admin

6👍

The issue is in how you set the password. You’ve excluded the password from the list of fields on the model form, so it is not set on save. So doing user.set_password(user.password) is effectively setting the password to the hash of None. Instead, do this:

user = user_form.save(commit=False)
user.set_password(user_form.cleaned_data['password']
user.save()

Note that even in your original code there was no way setting the password could cause IntegrityError, so that try/except was unnecessary; it’s even more so now, so you should remove it.

-1👍

Use the below code to solve it..

def register(request, template_name="registration/register.html"):
    if request.method == "POST":
        postdata = request.POST.copy()
        username = postdata.get('username', '')
        email = postdata.get('email', '')
        password = postdata.get('password', '')

        # check if user does not exist
        if User.objects.filter(username=username).exists():
            username_unique_error = True

        if User.objects.filter(email=email).exists():
            email_unique_error = True

        else :
            create_new_user = User.objects.create_user(username, email, password)
            create_new_user.save()
            user = authenticate(username=username, password=password)
            login(request, user)
            if create_new_user is not None:
                if create_new_user.is_active:
                    return HttpResponseRedirect('/profile')
                else:
                    print("The password is valid, but the account has been disabled!")


    return  render(request, template_name, locals())


def log_in(request, template_name="registration/login.html"):
    page_title = "Login"
    if request.method == "POST":
        postdata = request.POST.copy()
        username = postdata.get('username', '')
        password = postdata.get('password', '')

        try:
            user = authenticate(username=username, password=password)
            login(request, user)

            return HttpResponseRedirect('/profile')
        except :
            error = True

    return render(request, template_name, locals())

Leave a comment