3

I received the following django error

File "./project/auth_backend.py", line 31, in authenticate
user.save()
...
IntegrityError: (1062, "Duplicate entry 'user_name' for key 'username'") 

The said file contains the following code (which is based on https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#writing-an-authentication-backend)

try:
    user = User.objects.get(username=username)
except User.DoesNotExist:
    user = User(username=username, password=password)
...
user.save()

It seems that somehow it raised User.DoesNotExist even when it actually does exist. My database is MySQL.

I've seen others with a similar problem but unlike them, I'm not using any database caching.

Dynameyes
  • 435
  • 5
  • 15
  • 1
    Did you try creating a `User` via the documented `create_user` method? `user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')` :: https://docs.djangoproject.com/en/1.9/topics/auth/default/#user-objects – Hybrid Jan 19 '16 at 06:04
  • This problem occurs always or only sometimes? Please show all `authenticate` function. – Tomasz Jakub Rup Jan 19 '16 at 07:35
  • @hybrid I haven't tried it yet. How different will it be from my current code? Note that in this example, I don't think it should have raised User.DoesNotExist in the first place which means that if it behaves correctly, it would not reach the user creation part. – Dynameyes Jan 19 '16 at 10:20
  • @TomaszJakubRup It happened once and I can't replicate it now. My authenticate function is mostly the same as the custom authentication example from django docs https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#writing-an-authentication-backend – Dynameyes Jan 19 '16 at 10:22

1 Answers1

0

I had a similar problem like this. It was due to a inconsistency in my database. The _seq was out of date in the database. To fix this, try using the sqlsequencereset function in your manage.py. It prints all the commands which you should execute on your database... See here for more information.

Remi Smirra
  • 2,499
  • 1
  • 14
  • 15