如何覆盖Django AuthenticationForm class中的confirm_login_allowed函数?

How to overwrite the confirm_login_allowed function in the Django AuthenticationForm class?

我需要在用户不活动时覆盖 confirm_login_allowed 错误消息。我目前没有任何自定义登录视图或表单。我确实有一个自定义模型后端并覆盖了身份验证功能,但它在我的中间件文件中。

我不想将它添加到中间件,因为我只需要在登录时使用它。

如有任何帮助,我将不胜感激。

推荐阅读登录源码: https://docs.djangoproject.com/en/1.8/_modules/django/contrib/auth/views/

解决方法: 您需要在 django.contrib.auth.forms 中创建一个作为 AuthenticationForm 子类的表单,并在其中添加覆盖 confirm_login_allowed,如下所示:

在forms.py中:

class CustomAuthenticationForm(AuthenticationForm):
    def confirm_login_allowed(self, user):
        if not user.is_active:
            raise forms.ValidationError(
                _("Your account has expired. \
                Please click the renew subscription link below"),
                code='inactive',
            )

更新您的 urls.py 文件 - 更新登录视图的 kwargs:

url(r'^login/$', login, {'authentication_form':forms.CustomAuthenticationForm}, name='user_login'),