Django扩展AbstractUser并在其他字段

时间:2016-03-18 17:42:04

标签: python django django-models django-allauth django-rest-auth

我正在使用Django 1.9.2和python 2.7.3,rest框架和allauth。我从django.contrib.auth.models.AbstractUser扩展,我想从AbstractUser获取电子邮件字段并在其他字段中将其用作默认值:

from django.contrib.auth.models import AbstractUser


class MyUser(AbstractUser):

    def get_email(self):
        return self.email

    email_from_work = models.EmailField(default=get_email())

但是当我使用这段代码时,我收到以下错误:

File "./behnowapp/models.py", line 48, in MyUser
    email_from_work = models.EmailField(default=get_email())
TypeError: get_email() takes exactly 1 argument (0 given)

获取电子邮件属性的方式是什么?

2 个答案:

答案 0 :(得分:1)

您无法为此扩展AbstractBaseUser。为此扩展PermissionsMixin。如果要使用这些功能,请继承BaseUserManager。并且还可以使自定义管理器扩展class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] # Fields necessary for making a user def get_email(self): return self.email

示例 -

{{1}}

答案 1 :(得分:1)

感谢RA123的定位,我也覆盖了MyUser的保存方法,而不是实现我自己的UserManager,我已经实现了默认值,并且我添加了必要的字段:

class MyUser(AbstractBaseUser, PermissionsMixin):

    def save(self, *args, **kwargs):
        if not self.email_from_work:
            self.email_from_work = self.get_email()
        super(MyUser, self).save(*args, **kwargs)

    def get_email(self):
        return self.email

    objects = UserManager()
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    username = models.CharField(
        _('username'),
        max_length=30,
        unique=True,
        help_text=_('Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        validators=[
            validators.RegexValidator(
                r'^[\w.@+-]+$',
                _('Enter a valid username. This value may contain only '
                  'letters, numbers ' 'and @/./+/-/_ characters.')
            ),
        ],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    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=now)
    email_from_work = models.EmailField(max_length=255, unique=True)