即使没有为用户设置可用密码,也强制 Django 发送重置密码电子邮件

force django to send reset password email even if usable password is not set for a user

如果没有为用户设置可用密码,Django 会自动失败并且不会发送重置密码电子邮件。我们如何覆盖此条件?

Django 假定在未设置密码的情况下需要使用 LDAP 身份验证。但在我们的例子中,用户可以通过社交身份验证登录,不会 为用户设置密码。如果他们希望使用电子邮件和密码登录,则通过电子邮件重置密码是唯一的选择。 我们如何做到这一点?

一种可能的方法是在用户注册时设置一个随机密码,但我们不想这样做,因为它不是很直观。

参考文献:

这是您需要做的。查看 https://docs.djangoproject.com/en/1.8/_modules/django/contrib/auth/forms/

class PasswordResetForm 有一个方法 get_users:

def get_users(self, email):

    """Given an email, return matching user(s) who should receive a reset.

    This allows subclasses to more easily customize the default policies
    that prevent inactive users and users with unusable passwords from
    resetting their password.

    """
    active_users = get_user_model()._default_manager.filter(
        email__iexact=email, is_active=True)
    return (u for u in active_users if u.has_usable_password())

用这个函数覆盖这个方法:

def get_users(self, email):

    """Given an email, return matching user(s) who should receive a reset.

    This allows subclasses to more easily customize the default policies
    that prevent inactive users and users with unusable passwords from
    resetting their password.

    """
    active_users = get_user_model()._default_manager.filter(
        email__iexact=email, is_active=True)
    return active_users

为此,您将构建一个自定义表单并覆盖此方法。

class PasswordResetFormAllowNoPassword(PasswordResetForm):

    def get_users(self, email):
        active_users = get_user_model()._default_manager.filter(
            email__iexact=email, is_active=True)
        return active_users