0

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

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

4

2 回答 2

1

您不能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
于 2016-03-18T19:52:08.143 回答
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)
于 2016-03-21T19:03:10.937 回答