django.db.utils.IntegrityError:(1062,键“用户名”的“重复条目””)

时间:2019-04-03 07:12:34

标签: python django

我在Django应用程序中具有以下自定义用户模型实现:

users / models.py

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email: str,
                     password: str, is_staff: bool,
                     is_superuser: bool, **extra_fields):
        """Creates and saves a User with the given email and password.
        """
        email = self.normalize_email(email)
        user = self.model(email=email, is_staff=is_staff, is_active=True,
                          is_superuser=is_superuser, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email: str, password=None, **extra_fields):
        return self._create_user(email, password, False, False, **extra_fields)

    def create_superuser(self, email: str, password: str, **extra_fields):
        return self._create_user(email, password, True, True, **extra_fields)


class User(AbstractUser, UUIDModel):
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    email = models.EmailField(unique=True, db_index=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)
    date_joined = models.DateTimeField(default=timezone.now)

    USERNAME_FIELD = 'email'
    objects = UserManager()

    class Meta:
        verbose_name = 'user'
        verbose_name_plural = 'users'
        ordering = ('-date_joined', )

    def get_full_name(self):
        return "{} {}".format(self.first_name, self.last_name)

    def get_short_name(self):
        return self.first_name

    def get_email(self):
        return self.email

    def __str__(self):
        return "{}".format(self.email)

我在admin.py中的更改表单如下:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
from django.contrib.auth.forms import UserChangeForm as DjangoUserChangeForm
from django.contrib.auth.forms import UserCreationForm as DjangoUserCreationForm

from .models import User


# Forms
# ----------------------------------------------------------------------------
class MyUserCreationForm(DjangoUserCreationForm):
    class Meta:
        model = User
        fields = ("email",)


class MyUserChangeForm(DjangoUserChangeForm):
    class Meta:
        model = User
        fields = '__all__'


# ModelAdmins
# ----------------------------------------------------------------------------
@admin.register(User)
class UserAdmin(AuthUserAdmin):
    add_form_template = 'admin/auth/user/add_form.html'
    model = User
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {'fields': ('first_name', 'last_name',)}),
        ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser',
                                    'groups', 'user_permissions')}),
        ('Important dates', {'fields': ('last_login', 'date_joined')}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'password1', 'password2'),
        }),
    )
    readonly_fields = ('date_joined', 'last_login')
    form = MyUserChangeForm
    add_form = MyUserCreationForm
    list_display = ('email', 'first_name', 'last_name', 'is_active')
    list_filter = ('is_superuser', 'is_active')
    search_fields = ('first_name', 'last_name', 'email')
    ordering = ('email',)

我在settings.py文件中添加了这两行。

AUTH_USER_MODEL = 'users.User'
AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",)

我已将此模型扩展为自定义配置文件模型。但是,当我尝试创建另一个用户时,出现以下错误django.db.utils.IntegrityError: (1062, "Duplicate entry '' for key 'username'")。有人可以帮我吗?

我正在使用Django:Django == 2.2和MySql。

1 个答案:

答案 0 :(得分:0)

设置

USERNAME_FIELD = 'username'

并测试您的代码。

如果一切正常,请进行更改。