I want to change my django user model to allow registration / registration by phone or email. Using
USERNAME_FIELD = 'identifier'
If a user logs in with a phone number, the identifier will be his phone number or email address, vice versa. (If someone thinks I should just assign some number as an identifier, let me know.)
Here are my accounts:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from phonenumber_field.modelfields import PhoneNumberField
class UserManager(BaseUserManager):
def create_user(self, email, phone, password, **kwargs):
"""
Creates and saves a Account with the given email or phone and password.
"""
now = timezone.now()
identifier = ''
if not email:
if not phone:
raise ValueError('Users must have a valid email or phone address.')
else:
identifier = phone
if not phone:
if not email:
raise ValueError('Users must have a valid email or phone address.')
else:
email = self.normalize_email(email)
identifier = email
user = self.model(email=email, phone=phone,
identifier=identifier,
joined=now,
**kwargs
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **kwargs):
user = self.model(
email=email,
is_staff=True,
is_superuser=True,
**kwargs
)
user.set_password(password)
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(null=True, blank=True, unique=True)
phone = PhoneNumberField(null=True, blank=True, unique=True)
joined = models.DateTimeField(auto_now_add=True)
first_name = models.CharField(max_length=200, null=True, blank=True)
last_name = models.CharField(max_length=200, null=True, blank=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
identifier = models.CharField(max_length=40, unique=True)
USERNAME_FIELD = 'identifier'
def get_username(self):
return self.email
def get_short_name(self):
return self.first_name
short_name = property(fget=get_short_name)
, , , -auth rest-auth. , . - all-auth, , / , , .
: