【发布时间】:2016-03-23 15:57:46
【问题描述】:
在 django-rest-auth 框架中,什么是最好的(最简单的?)方法来要求只有一个电子邮件用于用户注册,而不是要求用户名?
例如,我是否需要编写一个新的用户序列化程序?是否有一个标志设置可以让我设置 True 或 False 来关闭或开启此要求?
谢谢
【问题讨论】:
标签: python django-rest-framework django-allauth django-rest-auth
在 django-rest-auth 框架中,什么是最好的(最简单的?)方法来要求只有一个电子邮件用于用户注册,而不是要求用户名?
例如,我是否需要编写一个新的用户序列化程序?是否有一个标志设置可以让我设置 True 或 False 来关闭或开启此要求?
谢谢
【问题讨论】:
标签: python django-rest-framework django-allauth django-rest-auth
您需要编写自己的 AbstractUser 和 BaseUserManager 类。幸运的是it's pretty simple,在你的应用模型中添加这样的东西:
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!
【讨论】:
ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email'
auth.model.User 和任何其他 Model 您已编写用于跟踪用户配置文件信息。不过我不能和allauth 说话。