0

I'm wondering how I can update a Django Users username. I am using the default auth model, with a OneToOne relationship for a custom Profile. The Profile can be updated via the end user, and a signal has been set to listen to the change and update accordingly.

Even if the username is gibberish or isn't changed at all the same error occurs, so I'm not sure why the unique constraint is being violated.

# models

class Profile(models.Model):
    client = models.OneToOneField('auth.User', related_name='profile')


# signals

@receiver(pre_save, sender=Profile, weak=False)
def sync_profile_auth(sender, instance, **kwargs):
    if instance.pk:
        instance.client.first_name = instance.first_name
        instance.client.last_name = instance.last_name
        instance.client.email = instance.email
        instance.client.username = instance.email
        instance.client.save()

# error
django.db.utils.IntegrityError: duplicate key value violates unique constraint "auth_user_username_key"
DETAIL:  Key (username)=(myuser@admin.com) already exists.

Cheers.

Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78
Jamie S
  • 760
  • 3
  • 9
  • 19

1 Answers1

0

First problem:

Maybe you are trying to update a user , already exists in database.

Second problem:

username = models.CharField(_('username'), max_length=30, unique=True,
    help_text=_('Required. 30 characters or fewer. Letters, numbers and '
                '@/./+/-/_ characters'),
    validators=[
        validators.RegexValidator(re.compile('^[\w.@+-]+$'), _('Enter a valid username.'), 'invalid')
    ])

The variable username, has max_length=30. if the user has a email with more than 30 characters, he can't register.

This can be helpful for you.
Customize User Model

Paulo Pessoa
  • 2,509
  • 19
  • 30
  • 1
    Hi Paolo, I have a set of custom migrations that modify the database tables to allow for longer usernames. – Jamie S Sep 24 '15 at 05:06
  • returning to the problem, what happening if you try to update a object without change the username? u got a key error again, alright? – Paulo Pessoa Sep 24 '15 at 05:22