3

I'm using django-registration-redux in my project for user registration. It uses default User model which use username as the unique identifier.

Now we want to discard username and use email as the unique identifier.

And also we want to use email instead of username to login.

How to achieve this?

And is it possible to do it without changing the AUTH_USER_MODEL settings?

Because from the official doc it says

If you intend to set AUTH_USER_MODEL, you should set it before creating any migrations or running manage.py migrate for the first time.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
dingx
  • 1,621
  • 3
  • 20
  • 38

3 Answers3

7

You can override 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 settings file (read this link for details)

REGISTRATION_FORM = 'app.forms.MyRegForm'

This will set the email to username field as well and then everything will work as email is now the username.

The only problem is that username field has a max lenght of 30 in DB. So emails longer than 30 chars will raise DB exception. To solve that override the user model (read this for details).

Lucas Gabriel Sánchez
  • 40,116
  • 20
  • 56
  • 83
Rajesh Kaushik
  • 1,471
  • 1
  • 11
  • 16
  • Thanks for your reply. This is in fact a hack way, but actually it works. Simply it will set username to be the the same as given email address. And all the rest works as before, no need to customize User model. – dingx Jul 12 '15 at 03:56
  • I've got an error in relation to "Required=False" and had to correct to "require=False". The solution worked. Thanks. – baltasvejas Oct 16 '15 at 16:28
1

The easiest way to achieve this is to made your own custom User Model.

This is the 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

Edwin Lunando
  • 2,726
  • 3
  • 24
  • 33
  • 1
    the official doc says"If you intend to set AUTH_USER_MODEL, you should set it before creating any migrations or running manage.py migrate for the first time", so will this break the migration – dingx Jul 11 '15 at 14:55
0

You will want to use AbstractBaseUser. Docs are here:

https://docs.djangoproject.com/en/1.8/topics/auth/customizing/

Good luck!

FlipperPA
  • 13,607
  • 4
  • 39
  • 71