我已经扩展了 django 1.5 用户模型,如下所示,当我将任何行插入数据库时遇到问题。我的 models.py 文件如下所示。
class MyUserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=MyUserManager.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(email,
password=password
)
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='Email address',
max_length=255,
unique=True,
db_index=True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
def get_full_name(self):
# The user is identified by their email address
return self.email
def __unicode__(self):
return self.email
我的 admin.py 如下所示。
class MyUserAdmin(UserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('email', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Permissions', {'fields': ('is_admin',)}),
('Important dates', {'fields': ('last_login',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
// Now register the new UserAdmin...
admin.site.register(MyUser, MyUserAdmin)
// ... and, since we're not using Django's builtin permissions,
// unregister the Group model from admin.
admin.site.unregister(Group)
我从 django 教程中遵循了上述内容(https://docs.djangoproject.com/en/dev/topics/auth/customizing/#a-full-example)
现在我遇到的问题是每当我在管理员中修改任何内容时,都会收到一条错误消息,如下所示。
(1452, '无法添加或更新子行:外键约束失败 ( csiop
. django_admin_log
, CONSTRAINT user_id_refs_id_c8665aa
FOREIGN KEY ( user_id
) REFERENCES auth_user
( id
))')
所以,看起来 django_admin_log 表总是需要外键引用到 auth_user 模型。但是因为我创建了一个客户用户模型,所以当我创建一个超级用户时,用户详细信息仅存储在客户 MyUser 表中,并且在 auth_user 模型中没有创建任何条目,这似乎是导致问题的原因。
我该如何解决这个问题?请建议。
谢谢斯里坎特