django.db.utils.IntegrityError:重复的键值违反了唯一约束“ core_user_pkey”详细信息:键(id)=(23)已存在

时间:2019-09-06 12:21:02

标签: python django django-models

我正在使用python 3.7,django 2.2.4,docker和postgresql进行项目,当我想创建超级用户时出现此错误 我做了23次(这就是id等于23的原因)。

这是我的模特:

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']

这是我的迁移代码:

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,
            },
        ),
    ]

这是我的管理员代码:

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)

通过在屏幕上显示数据库编号23中的对象计数(此刻)显示在屏幕上,但是当我要创建另一个超级用户时,会发生相同的错误,并且通过在此刻再次打印对象计数显示在屏幕上的数字24中,这意味着该对象已添加到数据库,但是当我进入管理页面并输入我的用户并通过该错误时,屏幕上会显示错误,并说该用户不存在。

当我创建超级用户时,这是完全错误:

 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.

2 个答案:

答案 0 :(得分:1)

在您的create_superuser方法中,对用户的保存调用缺少参数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

答案 1 :(得分:0)

很可能由于错误指示超级用户已经存在,您应该删除所有超级用户并创建一个新的超级用户。如果无法访问数据库,则可以运行命令:

python manage.py flush

请注意,此命令将清除ENTIRE数据库。 然后迁移数据库:

python manage.py makemigrations
python manage.py migrate

然后您可以尝试再次创建超级用户

python manage.py createsuperuser