question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Empty username used if existing username, leading to 'duplicate key value' 2nd time

See original GitHub issue
# Versions
django-rest-auth==0.9.1
django-allauth==0.32.0

# Settings
AUTH_USER_MODEL = 'accounts.User'
AUTH_PROFILE_MODEL = AUTH_USER_MODEL
ACCOUNT_AUTHENTICATION_METHOD = 'username_email'
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_SIGNUP_PASSWORD_VERIFICATION = False
ACCOUNT_USERNAME_REQUIRED = True
SOCIALACCOUNT_AUTO_SIGNUP = True
SOCIALACCOUNT_EMAIL_REQUIRED = True
SOCIALACCOUNT_UNIQUE_EMAIL = True

I have a non-social account using email@gmail.com and myusername

If I then try to create a new user using social authentication (facebook) with an account that has the same username & email the following happens:

  1. The first time I create the user, a user with an empty username is created. The email attached to the user is the same as the existing user (even though I have it specified that email should be unique)
  2. The second time I create the user, an IntegrityError is thrown, due to “username” already existing (which is blank).

I have tried turning on/off SOCIALACCOUNT_AUTO_SIGNUPas well.

The traceback is as follows:

Environment:

Request Method: POST Request URL: http://api.my_app.com/rest-auth/facebook/

Django Version: 1.9.5 Python Version: 2.7.6 Installed Applications: [u’django.contrib.admin’, u’django.contrib.auth’, u’django.contrib.contenttypes’, u’django.contrib.sessions’, u’django.contrib.messages’, u’django.contrib.staticfiles’, u’django.contrib.sites’, u’accounts’, u’comment’, u’friends’, u’flow’, u’hashtag’, u’notification’, u’page’, u’report’, u’share’, u’utilities’, u’channels’, u’corsheaders’, u’django_extensions’, u’djcelery_email’, u’elasticstack’, u’favit’, u’friendship’, u’haystack’, u’hitcount’, u’rest_framework’, u’rest_framework.authtoken’, u’rest_framework_swagger’, u’rest_auth’, u’rest_auth.registration’, u’allauth’, u’allauth.account’, u’allauth.socialaccount’, u’allauth.socialaccount.providers.facebook’, u’allauth.socialaccount.providers.twitter’, u’allauth.socialaccount.providers.google’, u’allauth.socialaccount.providers.reddit’, u’threadedcomments’, u’django_comments’, u’storages’, u’stream_django’, u’timezone_field’, u’versatileimagefield’, u’votes’] Installed Middleware: [u’django.middleware.security.SecurityMiddleware’, u’django.contrib.sessions.middleware.SessionMiddleware’, u’corsheaders.middleware.CorsMiddleware’, u’django.middleware.common.CommonMiddleware’, u’django.middleware.csrf.CsrfViewMiddleware’, u’django.contrib.auth.middleware.AuthenticationMiddleware’, u’django.contrib.auth.middleware.SessionAuthenticationMiddleware’, u’django.contrib.messages.middleware.MessageMiddleware’, u’django.middleware.clickjacking.XFrameOptionsMiddleware’]

Traceback:

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/core/handlers/base.py” in get_response 149. response = self.process_exception_by_middleware(e, request)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/channels/handler.py” in process_exception_by_middleware 224. return super(AsgiHandler, self).process_exception_by_middleware(exception, request)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/core/handlers/base.py” in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/views/decorators/csrf.py” in wrapped_view 58. return view_func(*args, **kwargs)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/views/generic/base.py” in view 68. return self.dispatch(request, *args, **kwargs)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/utils/decorators.py” in _wrapper 67. return bound_func(*args, **kwargs)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/views/decorators/debug.py” in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/utils/decorators.py” in bound_func 63. return func.get(self, type(self))(*args2, **kwargs2)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/rest_auth/views.py” in dispatch 49. return super(LoginView, self).dispatch(*args, **kwargs)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/rest_framework/views.py” in dispatch 466. response = self.handle_exception(exc)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/rest_framework/views.py” in dispatch 463. response = handler(request, *args, **kwargs)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/rest_auth/views.py” in post 92. self.serializer.is_valid(raise_exception=True)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/rest_framework/serializers.py” in is_valid 213. self._validated_data = self.run_validation(self.initial_data)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/rest_framework/serializers.py” in run_validation 410. value = self.validate(value)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/rest_auth/registration/serializers.py” in validate 115. login.save(request, connect=True)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/allauth/socialaccount/models.py” in save 238. user.save()

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/contrib/auth/base_user.py” in save 74. super(AbstractBaseUser, self).save(*args, **kwargs)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/db/models/base.py” in save 708. force_update=force_update, update_fields=update_fields)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/db/models/base.py” in save_base 736. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/db/models/base.py” in _save_table 820. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/db/models/base.py” in _do_insert 859. using=using, raw=raw)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/db/models/manager.py” in manager_method 122. return getattr(self.get_queryset(), name)(*args, **kwargs)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/db/models/query.py” in _insert 1039. return query.get_compiler(using=using).execute_sql(return_id)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py” in execute_sql 1060. cursor.execute(sql, params)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/db/backends/utils.py” in execute 79. return super(CursorDebugWrapper, self).execute(sql, params)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/db/backends/utils.py” in execute 64. return self.cursor.execute(sql, params)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/db/utils.py” in exit 95. six.reraise(dj_exc_type, dj_exc_value, traceback)

File “/home/ubuntu/.virtualenvs/my_app/local/lib/python2.7/site-packages/django/db/backends/utils.py” in execute 64. return self.cursor.execute(sql, params)

Exception Type: IntegrityError at /rest-auth/facebook/ Exception Value: duplicate key value violates unique constraint “accounts_user_username_key” DETAIL: Key (username)=() already exists.

Issue Analytics

  • State:open
  • Created 6 years ago
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
dudanogueiracommented, Feb 16, 2018

Ok, this is the piece of code I am using to try to avoid this error, I will try to reproduce the error while using the rest-auth facebook machinery. Right now I am only testing it against the shell, as above:

class User(AbstractUser):
    

    custom_field_1 = models.CharField(_('Como gostaria de ser Chamado?'), blank=True, max_length=255)
    custom_field_2 = models.ForeignKey('cadastro.Operadora', on_delete=models.CASCADE, blank=True, null=True)
    custom_field_3 = models.IntegerField(help_text="ID do Sistema Externo de Marketing (MAUTIC)", blank=True, null=True)

    
    def __str__(self):
        if self.name:
            return self.name
        return self.username
    
    def save(self, *args, **kwargs):
        if not self.id:
            username = self.username
            username_exists = True
            counter = 1
            self.username = username
            while username_exists:
                try:
                    username_exists = User.objects.get(username=username)
                    if username_exists:
                        username = self.username + '_' + str(counter)
                        counter += 1
                except User.DoesNotExist:
                    self.username = username
                    break
        super(User, self).save(*args, **kwargs)

Testing on shell goes like this:

In [7]: h = User.objects.create()

In [8]: h
Out[8]: <User: _2>

In [9]: h = User.objects.create(username="django-rest-awesome")

In [10]: h
Out[10]: <User: django-rest-awesome>

In [11]: h = User.objects.create(username="django-rest-awesome")

In [12]: h
Out[12]: <User: django-rest-awesome_1>

It’s a little bit hacky, but i think it can solve the problem for now. At least for my scenario.

Hope it helps 😃

0reactions
dudanogueiracommented, Feb 15, 2018

I think I have the same problem, and I am tracing it back to here:

File “/prod/venv_uerp/lib/python3.5/site-packages/rest_auth/registration/serializers.py” in validate 115. login.save(request, connect=True)

File “/prod/venv_uerp/lib/python3.5/site-packages/allauth/socialaccount/models.py” in save 238. user.save()

Are you guys using a custom user model?

In my case I don’t care for the username, as I am using the email to login or some social account. When using the regular facebook api, the allauth will hapilly create a new user, something like duda12345

I tried to test the API rest endpoint, but couldn’t for now. Will do later. I believe that if you do some sort of save override for the custom django user model it will be able to avoid this error, something in the lines of https://stackoverflow.com/questions/18182001/incrementing-the-slug-by-avoiding-integrity-error-in-django-models-save-method or the PR mentioned by @philippeluickx

thanks by this project, by the way. very well designed and integrated.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Django Allauth: Duplicate Key Value Violates Unique ...
I have been troubleshooting an issue with my custom allauth Django user model for some time. I only want to use email, first...
Read more >
Hidden dangers of duplicate key violations in PostgreSQL ...
The “duplicate key violates unique constraint” error notifies the caller that a retry is needed. This seems like an intuitive approach, but ...
Read more >
Error 'Duplicate Username' when you create a username
All Salesforce usernames are unique, for all users, across all Organizations (including Trial Orgs, Production orgs and Sandboxes). · Salesforce Username does ...
Read more >
MySQL 8.0 Reference Manual :: 13.2.7 INSERT Statement
INSERT with an ON DUPLICATE KEY UPDATE clause enables existing rows to be ... If both the column list and the VALUES list...
Read more >
What is a Foreign Key? (With SQL Examples)
How foreign keys work How to use foreign keys with SQL How to handle ... to column_a only if the same value already...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found