【问题标题】:force django to send reset password email even if usable password is not set for a user即使没有为用户设置可用密码,也强制 django 发送重置密码电子邮件
【发布时间】:2020-10-30 06:42:51
【问题描述】:

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

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

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

参考资料:

【问题讨论】:

    标签: django authentication passwords


    【解决方案1】:

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

    类 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
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 2019-12-01
    • 2015-03-12
    相关资源
    最近更新 更多