我正在尝试使用其他字段和功能来扩展默认的Django的身份验证模型,因此我决定继续扩展用户模型并编写自己的身份验证后端 .
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
class MyUser(User):
access_key = models.CharField(_('Acces Key'), max_length=64)
这是一个基本的代码,但在尝试syncdb时,我正在考虑一个谷歌不知道的奇怪错误:
CommandError: One or more models did not validate: core.sldcuser: 'user_ptr' defines a relation with the model 'auth.User', which has been swapped out. Update the relation to point at settings.AUTH_USER_MODEL.
在我的settings.py中,我添加了我想要的内容:
AUTH_USER_MODEL = 'core.MyUser'
有没有人偶然发现这个错误?
或者也许我应该使用一对一的方式,或1t1与代理的混合?
1 回答
你现在正在做的是创建一个User的子类,它是非抽象的 . 这意味着创建一个名为
ForeignKey
的表,该ForeignKey
指向auth.User
表上的主键 . 但是,您通过设置AUTH_USER_MODEL
所做的事情是告诉django.contrib.auth
不要创建该表,因为您将使用MyUser
. 可以理解Django有点困惑:P您需要做的是从
AbstractUser
或AbstractBaseUser
继承 .如果您想要用户已经拥有的所有内容,并且只想添加更多字段,请使用
AbstractUser
如果要从干净状态开始,只使用
AbstractBaseUser
,并且只继承用户的通用函数,但实现自己的字段 .REF:
https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model
https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substituting-a-custom-user-model