1
votes

I wanted to know how do we customize the error message that shows up when we enter 2 different passwords in the password1 and password2 fields from the built-in UserCreationForm in Django. I have tried this

def __init__(self,*args, **kwargs):
    super(CreateUserForm,self).__init__(*args, **kwargs)

    self.fields['password2'].error_messages.update({
        'unique': 'Type smtn here!'
    })

Am I doing something wrong in this process? In my template, this is the code for the error message.

<span id="error">{{form.errors}}</span>

Please tell me if there is another way to do this. I am using model forms.

class CreateUserForm(UserCreationForm):
  class Meta:
    model = User
    fields = ['username','email','password1','password2']
  def __init__(self,*args, **kwargs):
    super(CreateUserForm,self).__init__(*args, **kwargs)

    self.fields['password2'].error_messages.update({
        'unique': 'Type smtn here!'
    })
1

1 Answers

0
votes

As you can see in the source code of django's UserCreationForm.

This error message is triggered by clean_password2() and uses self.error_messages['password_mismatch']. This means you basically have to override error_messages in your child form:

class CreateUserForm(UserCreationForm):

    error_messages = {
        'password_mismatch': 'Type smtn here!',
    }

Alternatively, if you want to make sure not to loose possible other entries in error_messages dict (though it's currently the only entry), you can also update the dict in the __init__:

class CreateUserForm(UserCreationForm):

    def __init__(self, *args, **kwargs):
        self.error_messages['password_mismatch'] = 'Type smtn here!'
        super().__init__(*args, **kwargs)