0

我使用自定义用户模型来维护 django 1.5 的用户详细信息,下面是我的代码。使用社交身份验证时,一切似乎都工作正常,接受 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',] 
4

1 回答 1

1

Django-social-auth 在创建用户时不会这样工作,而是在调用create_user您的经理时,它只是传递用户名和电子邮件,如您在此处看到的那样。稍后在管道中,当调用this 时,用户模型中的更多字段会更新,但正如代码所述,它会getattr(user, name, None)在您的情况下执行first_nameand ,因为这些字段未在您的模型中定义,所以会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])
于 2013-04-14T17:26:47.963 回答