Django Redux registration: how to change unique id from username to email and use email as login
I am using Django-registration-redux in my project for user registration. It uses the default user model, which uses the username as a unique identifier.
Now we want to revoke the username and use email as a unique identifier.
And also we want to use email instead of username to login. How do you achieve this?
And can this be done without changing the AUTH_USER_MODEL settings ?
The official doc says, " If you intend to set AUTH_USER_MODEL, you must set it before creating any migrations, or run mig.py the first time. "
source to share
You can override the registration form like this
from registration.forms import RegistrationForm
class MyRegForm(RegistrationForm):
username = forms.CharField(max_length=254, required=False, widget=forms.HiddenInput())
def clean_email(self):
email = self.cleaned_data['email']
self.cleaned_data['username'] = email
return email
And then add this to your settings file (see link for details)
REGISTRATION_FORM = 'app.forms.MyRegForm'
This will also set the email in the username field, and then everything works as the email is now the username.
The only problem is that the username field has a maximum length of 30 in the DB. So emails longer than 30 characters will throw a DB exception. To solve this problem, override the user model (see this for details ).
source to share
The easiest way to achieve this is to create your own custom user model .
This is an example
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
date_of_birth = models.DateField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
Then you need to set the user model in your Django settings. https://docs.djangoproject.com/en/1.8/ref/settings/#auth-user-model
source to share
You want to use AbstractBaseUser. The docs are here:
https://docs.djangoproject.com/en/1.8/topics/auth/customizing/
Good luck!
source to share