0

在 django-rest-auth 框架中,什么是最好的(最简单的?)方法来要求只有用户注册的电子邮件而不是用户名?

例如,我是否需要编写一个新的用户序列化程序?是否有一个标志设置,我可以设置 True 或 False 来关闭或关闭此要求?

谢谢

4

1 回答 1

1

您需要编写自己的课程AbstractUserBaseUserManager课程。幸运的是它很简单,在你的应用模型中添加这样的东西:

from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models

class Account(AbstractBaseUser):
    email = models.EmailField(unique=True)
    username = models.CharField(max_length=40, unique=True, blank=True)

    first_name = models.CharField(max_length=40, blank=True)
    last_name = models.CharField(max_length=40, blank=True)

    is_admin = models.BooleanField(default=False)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = AccountManager()

    # This tells Django that this field is absolutely important...
    USERNAME_FIELD = 'email'
    # ...and username is now optional because it doesn't show up here!
    REQUIRED_FIELDS = []

    def __unicode__(self):
        return self.email

    def get_full_name(self):
        return ' '.join([self.first_name, self.last_name])

    def get_short_name(self):
        return self.first_name

class AccountManager(BaseUserManager):
    def create_user(self, email, password=None):
        if not email:
            raise ValueError('User must provide an e-mail address')

        account = self.model(
            email=self.normalize_email(email)
        )

        account.set_password(password)
        account.save()

        return account

    def create_superuser(self, email, password=None):
        account = self.create_user(email, password)

        account.is_admin = True
        account.save()

        return account

接下来,告诉 Django 这个模型是你项目的User类。将以下内容添加到您的settings.py文件中:

AUTH_USER_MODEL = 'apiapp.Account'

完成后,只需迁移:

python manage.py makemigrations
python manage.py migrate

从那时起,这个新模型将代表新用户(您必须手动处理迁移),包括您可能使用的任何地方self.request.user

于 2016-03-24T02:42:09.993 回答