当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Django AuthenticationForm.confirm_login_allowed用法及代码示例


本文介绍django.contrib.auth.forms.AuthenticationForm.confirm_login_allowed的用法。

声明

confirm_login_allowed(user)

默认情况下,AuthenticationForm 拒绝 is_active 标志设置为 False 的用户。您可以使用自定义策略覆盖此行为以确定哪些用户可以登录。使用子类 AuthenticationForm 并覆盖 confirm_login_allowed() 方法的自定义表单执行此操作。如果给定用户可能无法登录,此方法应引发 ValidationError

例如,要允许所有用户登录而不管“active” 状态如何:

from django.contrib.auth.forms import AuthenticationForm

class AuthenticationFormWithInactiveUsersOkay(AuthenticationForm):
    def confirm_login_allowed(self, user):
        pass

(在这种情况下,您还需要使用允许非活动用户的身份验证后端,例如 AllowAllUsersModelBackend 。)

或者只允许一些活动用户登录:

class PickyAuthenticationForm(AuthenticationForm):
    def confirm_login_allowed(self, user):
        if not user.is_active:
            raise ValidationError(
                _("This account is inactive."),
                code='inactive',
            )
        if user.username.startswith('b'):
            raise ValidationError(
                _("Sorry, accounts starting with 'b' aren't welcome here."),
                code='no_b_users',
            )

相关用法


注:本文由纯净天空筛选整理自djangoproject.com大神的英文原创作品 django.contrib.auth.forms.AuthenticationForm.confirm_login_allowed。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。