[Answered ]-Getting DUPLICATE error when logging in existing user with Django

1πŸ‘

βœ…

To check the existence you could do

user = User.objects.filter(username=username).exists()
here user will be a bool

and to count it

user = User.objects.filter(username=username).count()
here user will be a int.

But you should never get a duplicate user you should probably do more checks

here you can check if the exists and also their count if count is 1 then only it should login.

And if there is no existence then only create the user

Yea also I would suggest to

user = authenticate(username=username, password=password)    
if user:
    login(request,user)
    return HttpResponse('success')
πŸ‘€Bijoy

1πŸ‘

What you’re trying to do in that line:

            user,created = User.objects.get_or_create(username=username, password=password)

is to find user in your database, which username matches specified username, and password matches password. But passwords are not stored as a plaintext, so basically that lookup will fail every time. When lookup fails, django will try to create new user with specified username and password, but user with given username might already exist.

            user,created = User.objects.get_or_create(username=username)

And it should work fine.

πŸ‘€GwynBleidD

Leave a comment