如何自定义登录错误消息?

时间:2018-12-10 21:50:08

标签: django

我要更改“请输入正确的用户名和密码。请注意,两个字段都区分大小写”。

在login.html中,我有{{ form|crispy }};在urls.py中,我的URLs.py中有url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='login'),

enter image description here

2 个答案:

答案 0 :(得分:2)

您需要从auth.login到具有auth.LoginView子类的AuthenticationForm的新子类视图。

from django.contrib.auth.views import LoginView
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import gettext_lazy as _

class MyAuthForm(AuthenticationForm):
    error_messages = {
        'invalid_login': _(
            "Please enter a correct %(username)s and password. Note that both "
            "fields may be case-sensitive."
        ),
        'inactive': _("This account is inactive."),
    }


class MyLoginView(LoginView):
    authentication_form = MyAuthForm

您可以根据需要更改invalid_login条目。

在您的urls.py中:

url(r'^login/$', MyLoginView.as_view(), {'template_name': 'login.html'}, name='login'),

答案 1 :(得分:0)

@schillingt的回答很好。

我提供了另一个答案,它可能并不漂亮,但如果您很紧急,并且您不知道任何想法,至少此方法(contextmanager)可以帮助您工作。由于 django 使用大量的类属性来控制某些内容,因此它可能在许多情况下适用。

from django.contrib.auth import views
from contextlib import contextmanager
from django.contrib.auth.forms import AuthenticationForm
from django.template.response import TemplateResponse
from django.utils.translation import gettext_lazy


class LoginViewCustom(views.LoginView):
    template_name = 'my_login.html'
    error_messages = {
        'invalid_login': gettext_lazy('...'),
        'inactive': gettext_lazy("..."),
    }

    def post(self, request, *args, **kwargs):
        with self.handle_msg():
            rtn_response: TemplateResponse = super(LoginViewCustom, self).post(request, *args, **kwargs)
        return rtn_response

    @contextmanager
    def handle_msg(self):
        org_msg = AuthenticationForm.error_messages
        AuthenticationForm.error_messages = self.error_messages
        try:
            yield self.error_messages
        finally:
            AuthenticationForm.error_messages = org_msg

相关问题