Django 扩展 AbstractUser 并在其他字段中使用电子邮件字段作为默认值

Django Extend AbstractUser and use email Field as default in other field

我将 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)

email属性的获取方式是什么?

您不能为此目的扩展 AbstractUser。为此扩展 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

感谢RA123的指导,我也覆盖了MyUser的save方法,而不是实现我自己的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)