代码之家  ›  专栏  ›  技术社区  ›  User

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

  •  0
  • User  · 技术社区  · 7 年前

    {{ form|crispy }} 而且在网址.py我有 url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='login'), 在我的网址.py.

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  5
  •   schillingt    7 年前

    你需要从 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

    在你的网址.py:

    url(r'^login/$', MyLoginView.as_view(), {'template_name': 'login.html'}, name='login'),
    
        2
  •  0
  •   Carson    6 年前

    我提供另一个答案,它可能不漂亮,但是 如果你有急事 contextmanager )可以帮你工作。它可以适用于许多情况,因为 使用大量的类属性来控制某些东西。

    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