Change Form Validations

Hi again!

Does someone knows how to change the error messages that appears on forms?

This ones:

I already read a lot of documentation but didn’t find anything.
Here is the code:

forms.py

class DealerRegisterForm(UserCreationForm):
    email = forms.EmailField(required=True, max_length=50, help_text='Digite o seu e-mail')
    username = forms.CharField(required=True, max_length=20, help_text='This will display on your posts')
    error_messages = {
        'password_mismatch': ('As palavras-passe não são iguais.'),
        'password_too_common': ('As palavras passe sao comuns'), #This one is not working


    }

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

        self.fields['username'].label = 'Nome de utilizador'
        self.fields['email'].label = 'E-mail'


    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError("Este e-mail já esta registado.")
        return email

    def clean_username(self):
        username = self.cleaned_data['username']
        if len(username) > 25:
            raise forms.ValidationError('Digite um nome que contenha menos de 25 caractéres.')
        return username

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

views.py

def authentication(request):
        if request.method == 'POST':
            form = DealerRegisterForm(request.POST)
            if form.is_valid():
                form.save()
                username = form.cleaned_data.get('username')
                password = form.cleaned_data.get('password')
                user = form.save()
                login(request, user)
                messages.success(request, f'Account {username} created!')
                return redirect('home')
            else:
                pass
            return render(request, 'authentication.html', {'form': form})


        else:
            form = DealerRegisterForm()
        return render(request, 'authentication.html', {'form': form})

Maybe there is some function that I can add to my class in order to override the error message?

Another thing, is there a way so that the same username can be used several times, without saying ’ this username is already being used’? :smile:

Have a nice day!

The password_too_common error is not defined in UserCreationForm, so changing it in your subclass isn’t going to affect it.

The only thing I can think of to change other error messages would be to iterate over the message class in your view and change the text of any messages you want changed.

No, and given how usernames are used within the system, it really doesn’t make any sense to try. What are you trying to accomplish by doing this? (What benefit might you think you’ll see?)

Thank you for your feedback!

On the ‘username’ place I want to set the name of a user( for example John, Michael…) and there can be 2 Johns registered. Maybe I should just create another field called “name”, instead of use the build-in ‘username’ field in order to do that? :thinking:

Yes, that’s not the purpose or intent of the Django username field. The username field is the identifier that the person uses to log on. The Django User model already has two other fields, first_name and last_name for storing an individual’s proper name.