當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。