Log in user using either email address or username in Django

后端 未结 13 2556
故里飘歌
故里飘歌 2020-12-02 08:34

I am trying to create an auth backend to allow my users to log in using either their email address or their username in Django 1.6 with a custom user model. The backend work

13条回答
  •  失恋的感觉
    2020-12-02 09:15

    Note that for the most solutions like these you should add email uniqueness validation for User model to avoid the authentication vulnerability

    # models.py
    from django.contrib.auth.models import AbstractUser
    
    
    class User(AbstractUser):
        objects = UserManager()
        email = models.EmailField(_('email address'), unique=True)
    
        class Meta:
            verbose_name = _('user')
            verbose_name_plural = _('users')
            db_table = 'auth_user'
            swappable = 'AUTH_USER_MODEL'
    

    and then you have to update settings.py defining the AUTH_USER_MODEL property

    AUTH_USER_MODEL = '[your_app_name].User'
    

提交回复
热议问题