通过电子邮件登录自定义用户模型的正确方法是什么?

时间:2017-10-24 01:18:34

标签: django django-authentication django-users

我不需要让用户使用用户名登录,只需要电子邮件。 所以我有自定义用户模型:

ImportResults 1,'Spring 2017'

自定义经理:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField('email address', unique=True)
    accepted = models.BooleanField('status', default=False)
    is_staff = models.BooleanField(
        'staff status',
        default=False,
        help_text='Designates whether the user can log into this site.',
    )
    is_active = models.BooleanField(
        'active',
        default=True,
        help_text='Designates whether this user should be treated as active. '
                  'Unselect this instead of deleting accounts.',
    )
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    objects = MyUserManager()

    class Meta:
        verbose_name = 'user'
        verbose_name_plural = 'users'

    def __str__(self):
        return self.email

    def get_full_name(self):
        return self.email

    def get_short_name(self):
        return self.email

我使用class MyUserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) 方法呈现登录模板。 在模板中,我有两个名为auth_views.loginemail的输入字段。

但是当我提交表单时,我收到一个验证错误,指出需要用户名字段。

我发现password正在使用auth_views.login,其中配置了AuthenticationForm字段。所以我决定覆盖这个表单并将其传递给视图:

username

在模板中,我使用class MyAuthForm(AuthenticationForm): username = forms.EmailField() url(r'^login/$', auth_views.login, {'authentication_form': MyAuthForm}, name='login') 作为电子邮件字段的名称。那个闻起来很糟糕。

所以我的问题是我是否通过电子邮件正确登录?如果没有,那么正确的方法是什么?

更新:添加设置

username

2 个答案:

答案 0 :(得分:0)

如果所有这一切的目的是让用户使用他们的电子邮件登录,那么这可以在没有这一切的情况下完成。

使用django默认User模型。为用户登录添加视图和表单(带有字段电子邮件和密码)。在您的视图中,在您收到用户的电子邮件后,请查询django的User模型以获取其用户名。

使用视图中的django.contrib.auth.authenticatedjango.contrib.auth.login等内置函数登录用户。

答案 1 :(得分:0)

是的,你的方向正确。如果没有深入到项目和调试中,很难回答你的问题。

注意Django的以下部分。发送您的登录表单后,LoginView会将数据传递给AuthenticationForm。查看AuthenticationForm所有后端的settings.AUTHENTICATION_BACKENDS来电def authenticate()

现在,您有一个默认后端ModelBackend。您需要添加自己的后端并添加到settings.AUTHENTICATION_BACKENDS。您可以拥有任意数量的后端,但序列确实很重要。例如:

AUTHENTICATION_BACKENDS = (
    'your_project.backends.CustomBackend',  # will be called before the next
    'django.contrib.auth.backends.ModelBackend',
)

示例:

class CustomBackend(ModelBackend):

    def authenticate(self, **kw):
        # here you have to return user object or None
        ...

    def get_user(self, user_id):
        try:
            return User._default_manager.get(pk=user_id)
        except User.DoesNotExist:
            return None
相关问题