使用自定义用户模型来维护django 1.5的用户详细信息,下面是我的代码。使用社交身份验证时,一切似乎都正常工作,接受first_name和last_name。
在我的表结构中,我没有first_name和last_name,而是有一个字段全名。
但是,我确实在管理器中创建了一个方法来接受名字和姓氏并将它们组合起来。但是,仍然在接受空值,对于为什么会发生这种情况的任何建议?
class UserManager(BaseUserManager):
"""
UserManager()
"""
def create_user(self, username, email=None, password=None, first_name='', last_name='', **extra_fields):
if not username:
raise ValueError('Users must have a username')
user = self.model(
username=username,
email=UserManager.normalize_email(email),
full_name='%s %s' % (first_name, last_name),
)
user.set_password(password)
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
"""
Accounts/User
"""
GENDERS = (
(u'M', _('Male')),
(u'F', _('Female')),
)
username = models.CharField(_('username'), max_length=30, unique=True,
help_text=_('Required. 30 characters or fewer. Letters, numbers and '
'@/./+/-/_ characters'),
validators=[
validators.RegexValidator(re.compile('^[\w.@+-]+$'), _('Enter a valid username.'), 'invalid')
])
email = models.EmailField(_('email address'), blank=True)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin '
'site.'))
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
# user details and information
full_name = models.CharField(_('full name'), max_length=30, )
date_of_birth = models.DateField(_('birthday'), null=True, blank=True)
bio = models.TextField(_('biography / about you'), null=True, blank=True, help_text=_('Biography / About you'))
gender = models.CharField(_('gender'), max_length=1, blank=True, null=True, choices=GENDERS)
# follows / followers
followings = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='followers')
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email', 'date_of_birth', 'full_name',]
答案 0 :(得分:1)
Django-social-auth在创建用户时不起作用,而在您的经理中调用create_user
时,它只是传递用户名和电子邮件,如您所见here。稍后在管道中,当called为{{3}}时,您的用户模型中的更多字段会更新,但正如代码所示,它会getattr(user, name, None)
执行first_name
和last_name
},返回None
,因为这些字段未在模型中定义。
您可以通过在模型中定义一些属性来欺骗系统,如下所示:
class User(...):
@property
def first_name(self):
if not hasattr(self, '_first_name'):
self._first_name = self.full_name.split(' ', 1)[0]
return self._first_name
@first_name.setter
def first_name(self, value):
self._first_name = value
self.build_full_name()
@property
def last_name(self):
if not hasattr(self, '_last_name'):
self._last_name = self.full_name.split(' ', 1)[-1]
return self._last_name
@first_name.setter
def last_name(self, value):
self._last_name = value
self.build_full_name()
def build_full_name(self):
self.full_name = ' '.join([self._first_name, self._last_name])