Ali
Ali

Reputation: 21

django.db.utils.IntegrityError: duplicate key value violates unique constraint "core_user_pkey" DETAIL: Key (id)=(23) already exists

i'm working on project using python 3.7 , django 2.2.4 , docker and postgresql and when i want to create super user i get this error i do it for 23 times(that's why the id equal to 23).

here is my model :

class UserManager(BaseUserManager):

    def create_user(self, email, username, name, password=None):
        """ create and save new user"""
        if not email:
            raise ValueError('User must have an email address')
        user = self.model(email=self.normalize_email(email),
                          name=name,
                          username=username)
        user.set_password(password)
        user.save(using=self._db)

        return user

    def create_superuser(self, email, username, name, password):
        """create and save new super user"""
        user = self.create_user(email, username, name, password)
        user.is_staff = True
        user.is_superuser = True

        user.save(self._db)

        return user


class User(AbstractBaseUser, PermissionsMixin):
    """custom user model that using username in username field"""
    email = models.EmailField(max_length=70, unique=True)
    username = models.CharField(max_length=50, unique=True)
    name = models.CharField(max_length=50)
    gender = models.PositiveIntegerField(validators= 
    [MaxValueValidator(3)], 
    null=True)
    # 1 for men 2 for woman 0 for not mention
    bio = models.TextField(null=True)
    lives_in = models.CharField(max_length=70, null=True)
    phone_number = models.PositiveIntegerField(validators= 
    [MaxValueValidator(99999999999)], null=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email', 'name']

here is my migration code:

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('auth', '0011_update_proxy_permissions'),
    ]

    operations = [
        migrations.CreateModel(
            name='User',
            fields=[
                ('id', models.AutoField(auto_created=True,     
            primary_key=True, serialize=False, verbose_name='ID')),
                ('password', models.CharField(max_length=128, 
            verbose_name='password')),
                ('last_login', models.DateTimeField(blank=True, null=True, 
            verbose_name='last login')),
                ('is_superuser', models.BooleanField(default=False, 
            help_text='Designates that this user has all permissions 
            without explicitly assigning them.', verbose_name='superuser 
            status')),
            ('email', models.EmailField(max_length=70, unique=True)),
            ('username', models.CharField(max_length=50, unique=True)),
            ('name', models.CharField(max_length=50)),
            ('gender', models.PositiveIntegerField(null=True, validators=    
            [django.core.validators.MaxValueValidator(3)])),
            ('bio', models.TextField(null=True)),
            ('lives_in', models.CharField(max_length=70, null=True)),
            ('phone_number', models.PositiveIntegerField(null=True, 
            validators= 
            [django.core.validators.MaxValueValidator(99999999999)])),
            ('is_active', models.BooleanField(default=True)),
            ('is_staff', models.BooleanField(default=False)),
            ('groups', models.ManyToManyField(blank=True, help_text='The 
            groups this user belongs to. A user will get all permissions 
            granted to each of their groups.', related_name='user_set', 
            related_query_name='user', to='auth.Group', 
            verbose_name='groups')),
            ('user_permissions', models.ManyToManyField(blank=True, 
            help_text='Specific permissions for this user.', 
            related_name='user_set', related_query_name='user', 
            to='auth.Permission', verbose_name='user permissions')),
            ],
            options={
                'abstract': False,
            },
        ),
    ]

here is my admin code:

class UserAdmin(BaseUserAdmin):
    ordering = ['id']
    list_display = ['email', 'name']
    list_filter = ('is_active', 'is_superuser')
    fieldsets = (
        (None, {'fields': ('username', 'email', 'password')}),
        (_('Personal Info'), {'fields': ('name',)}),
        (
            _('Permissions'),
            {'fields': ('is_active', 'is_staff', 'is_superuser')}
        ),
        (_('Important dates'), {'fields': ('last_login',)})
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'name', 'email', 'password1',   
        'password2')
        }),
    )

 admin.site.register(models.User, UserAdmin)

by printing count of objects in database number 23(in this moment) shows on screen but when i want to create another super user the same error occurs and by printing count of objects again in this moment number 24 shows on screen that means the object added to database but when i go to the admin page and enter my user and pass the error appears on screen and say that this user is not exist.

here is complete error when i create super user:

 Traceback (most recent call last):
   File "/usr/local/lib/python3.7/site-          
 packages/django/db/backends/utils.py", line 84, in _execute
     return self.cursor.execute(sql, params)
   psycopg2.errors.UniqueViolation: duplicate key value violates unique           
 constraint "core_user_pkey"
 DETAIL:  Key (id)=(23) already exists.


 The above exception was the direct cause of the following exception:

 Traceback (most recent call last):
 File "manage.py", line 21, in <module>
   main()
 File "manage.py", line 17, in main
   execute_from_command_line(sys.argv)
 File "/usr/local/lib/python3.7/site- 
 packages/django/core/management/__init__.py", line 381, in                                              
 execute_from_command_line
    utility.execute()
 File "/usr/local/lib/python3.7/site- 
 packages/django/core/management/__init__.py", line 375, in execute
     self.fetch_command(subcommand).run_from_argv(self.argv)
   File "/usr/local/lib/python3.7/site- 
 packages/django/core/management/base.py", line 323, in run_from_argv
     self.execute(*args, **cmd_options)
   File "/usr/local/lib/python3.7/site- 
 packages/django/contrib/auth/management/commands/createsuperuser.py", 
 line 61, in execute
     return super().execute(*args, **options)
   File "/usr/local/lib/python3.7/site- 
 packages/django/core/management/base.py", line 364, in execute
     output = self.handle(*args, **options)
   File "/usr/local/lib/python3.7/site- 
 packages/django/contrib/auth/management/commands/createsuperuser.py", 
 line 156, in handle


 self.UserModel._default_manager.db_manager(database).create_superuser 
 (**user_data)
   File "/app/core/models.py", line 27, in create_superuser
     user.save(self._db)
   File "/usr/local/lib/python3.7/site- 
 packages/django/contrib/auth/base_user.py", line 66, in save
     super().save(*args, **kwargs)
   File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py",      
 line 741, in save
     force_update=force_update, update_fields=update_fields)
   File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", 
 line 779, in save_base
     force_update, using, update_fields,
   File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", 
 line 870, in _save_table
     result = self._do_insert(cls._base_manager, using, fields, update_pk, 
     raw)
   File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", 
 line 908, in _do_insert
     using=using, raw=raw)
   File "/usr/local/lib/python3.7/site- 
 packages/django/db/models/manager.py", line 82, in manager_method
     return getattr(self.get_queryset(), name)(*args, **kwargs)
   File "/usr/local/lib/python3.7/site- 
 packages/django/db/models/query.py", line 1186, in _insert
     return query.get_compiler(using=using).execute_sql(return_id)
   File "/usr/local/lib/python3.7/site- 
 packages/django/db/models/sql/compiler.py", line 1335, in execute_sql
     cursor.execute(sql, params)
   File "/usr/local/lib/python3.7/site- 
 packages/django/db/backends/utils.py", line 99, in execute
     return super().execute(sql, params)
   File "/usr/local/lib/python3.7/site- 
 packages/django/db/backends/utils.py", line 67, in execute
     return self._execute_with_wrappers(sql, params, many=False, 
 executor=self._execute)
   File "/usr/local/lib/python3.7/site- 
 packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
     return executor(sql, params, many, context)
   File "/usr/local/lib/python3.7/site- 
 packages/django/db/backends/utils.py", line 84, in _execute
     return self.cursor.execute(sql, params)
   File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 
 89, in __exit__
     raise dj_exc_value.with_traceback(traceback) from exc_value
   File "/usr/local/lib/python3.7/site- 
 packages/django/db/backends/utils.py", line 84, in _execute
     return self.cursor.execute(sql, params)
 django.db.utils.IntegrityError: duplicate key value violates unique 
 constraint "core_user_pkey"
 DETAIL:  Key (id)=(23) already exists.

Upvotes: 2

Views: 1602

Answers (2)

flopshot
flopshot

Reputation: 1655

In your create_superuser method, the save call to user is missing the parameter using

    def create_superuser(self, email, username, name, password):
        """create and save new super user"""
        user = self.create_user(email, username, name, password)
        user.is_staff = True
        user.is_superuser = True

        user.save(using=self._db). # <- DON'T FORGET TO ADD "USING"

        return user

Upvotes: 3

Liudvikas Bajarunas
Liudvikas Bajarunas

Reputation: 205

Well probably the superuser already exist as the error indicates, you should delete all the super users and create a new one. If you can't reach the database base, you can run command:

python manage.py flush

Be careful, this command cleans the ENTIRE database. then migrate the database:

python manage.py makemigrations
python manage.py migrate

And after that you can try creating the super user again

python manage.py createsuperuser

Upvotes: 1

Related Questions