django-rest-auth所需的电子邮件的最佳做法

时间:2016-03-23 15:57:46

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

什么是最好的(最简单的?)方式,要求只为用户注册发送电子邮件,而不是在django-rest-auth框架中将用户名作为要求?

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

由于

1 个答案:

答案 0 :(得分:0)

您需要编写自己的AbstractUserBaseUserManager课程。幸运的是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