Home > OS >  How to change Django default message in django.contrib.auth.form
How to change Django default message in django.contrib.auth.form

Time:12-28

I used Django default AuthenticationForm for login. Here is my code:

from django.contrib.auth.forms import (
    AuthenticationForm,PasswordResetForm,UsernameField
)
class ProfiledAuthenticationForm(AuthenticationForm):
    username = UsernameField(
        label=_("username"),
        max_length=254,
        widget=forms.TextInput(attrs={'autofocus': True,'placeholder': 'username'}),
    )
    password = forms.CharField(
        label=_("password"),
        strip=False,
        widget=forms.PasswordInput(attrs={'placeholder': 'password'}),
    )

When the login is failed, an default alert is appeared. I need to customize the alert. How should I handle it?

CodePudding user response:

Here is my code. It works well in my end.

class ProfiledAuthenticationForm(AuthenticationForm):
    username = UsernameField(
        label=_("メールアドレス"),
        max_length=254,
        widget=forms.TextInput(attrs={'autofocus': True,'placeholder': 'メールアドレス'}),
    )
    password = forms.CharField(
        label=_("パスワード"),
        strip=False,
        widget=forms.PasswordInput(attrs={'placeholder': 'パスワード'}),
    )
    #remember_me = forms.BooleanField(required=False,widget=forms.CheckboxInput(attrs={'class':'scalero-checkbox','id':'remember-me'}))
    profile_error_messages = {
        "invalid_profile": _("メールアドレスまたはパスワードが正しくありません。"
        )
    }
    error_messages = {
        'invalid_login': _(
            "ログインできません。パスワードが分からない場合、管理者に連絡してください。"            
        ),
        
    }

CodePudding user response:

You can change the message overwriting the error_messages property in your inherit class.

class ProfiledAuthenticationForm(AuthenticationForm):

    error_messages = {
        'invalid_login': _("My custom error message"),
        'inactive': _("This account is inactive."),
    }

  • Related