Django Registration Redux: how to change the unique identifier from username to email and use email as login

痴心易碎 提交于 2019-11-28 05:35:00

问题


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.


回答1:


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).




回答2:


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




回答3:


You will want to use AbstractBaseUser. Docs are here:

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

Good luck!



来源:https://stackoverflow.com/questions/31356535/django-registration-redux-how-to-change-the-unique-identifier-from-username-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!