2👍
✅
User model
First you need to create custom User manager and model.
Documentation can be found here https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#a-full-example
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
class EmailUserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email),)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(email, password=password,)
user.is_admin = True
user.is_superuser = True
user.save(using=self._db)
return user
class EmailUser(AbstractBaseUser, PermissionsMixin):
email = EmailField(
verbose_name='email',
max_length=255,
unique=True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
objects = EmailUserManager()
USERNAME_FIELD = 'email'
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
def __str__(self):
return self.email
@property
def is_staff(self):
return self.is_admin
And register it in your settings.py with this line AUTH_USER_MODEL = 'app.EmailUser'
.
Now your EmailUser model can be used with from django.contrib.auth import get_user_model
and from django.conf.settings import AUTH_USER_MODEL
.
Example usage (foreign key):
from django.db import models
from django.conf.settings import AUTH_USER_MODEL
class Profile(models.Model):
class Meta:
verbose_name = 'Profile'
verbose_name_plural = 'Profiles'
user = models.OneToOneField(AUTH_USER_MODEL, verbose_name='User',
related_name='profile')
full_name = models.CharField('Full name', max_length=64, blank=False)
phone = models.CharField('Phone', max_length=64, blank=True)
Registration
When using django-registration-redux two-step registration:
- Create
User
with None password on registration. This will make User model with unusable password https://docs.djangoproject.com/es/1.9/ref/contrib/auth/#django.contrib.auth.models.User.has_usable_password. It may be necessary to create customRegistrationForm
andRegistrationView
to avoid password checking. - On activation form submit (activation form template with password field) use methods
RegistrationManager.activate_user(key)
andUser.set_password(password)
Source:stackexchange.com