[Django]-How to customize the login error message?

8👍

You’ll need to change from auth.login to a new subclass view of auth.LoginView with a subclass of 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

You can change the invalid_login entry as needed for your message.

In your urls.py:

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

0👍

@schillingt’s answer is great.

I provide another answer, it may not be beautiful, but if you are urgent and you don’t have any idea, at least this method (contextmanager) can help you work. It can be suitable in many cases since django uses a lot of class property to control something.

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

👤Carson

Leave a comment