1

I'm trying to override (add languages) the messages of form.errors. I've tried this:

forms.py

class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']


    def __init__(self, *args, **kwargs):
        super(CreateUserForm, self).__init__(*args, **kwargs)
        self.error_messages['duplicate_username'] = 'some message'

After the form is submitted, it's not saved because username are unique and the error is displayed on the template. I'd like to make the same with the password but I can't find out the errors' key for each password validation. Can you provide me it?

VicenteC
  • 311
  • 7
  • 26
  • Does this answer your question? [Create Custom Error Messages with Model Forms](https://stackoverflow.com/questions/3436712/create-custom-error-messages-with-model-forms) – JPG Apr 07 '20 at 05:17
  • @ArakkalAbu I’m using UserCreationForm. Can I edit this form like that? – VicenteC Apr 07 '20 at 05:19
  • But I still need the keys (what I’m asking for) – VicenteC Apr 07 '20 at 05:24

1 Answers1

7

set error_messages--(Django doc) attribute in Meta class as,

class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']
        error_messages = {
            'username': {
                'unique': 'Your Custom Error Message here !!!',
            },
        }

If you want to override the password mismatch error message, override the error_messages attribute in the form class (not in the Meta class) as below,

class CreateUserForm(UserCreationForm):
    error_messages = {
        'password_mismatch': "Your Password Mismatch For 'UserCreationForm' class",
    }
    # other code
JPG
  • 82,442
  • 19
  • 127
  • 206
  • Do you have the docs of password validation errors? I’m trying to override them – VicenteC Apr 07 '20 at 05:43
  • how can I override the password's help text? Like "this password is too short, this password is too common, etc " – VicenteC Apr 07 '20 at 13:32
  • Please ask a different question since the OP issue has been solved. Apart from that, it would be a great start if you go through the official Django doc – JPG Apr 07 '20 at 13:35
  • I’ve been looking for that but I just founded information for the version 1.8 or 2.0 – VicenteC Apr 07 '20 at 13:38
  • official doc has the information of Django 1.8+ versions. – JPG Apr 07 '20 at 13:40