Home > front end >  Django doesn't render validation error of custom form validator
Django doesn't render validation error of custom form validator

Time:10-20

So I have the following form

class SignUpForm(UserCreationForm):
    email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={
        'class': tailwind_class
    }))
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': tailwind_class}))
    password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput(attrs={'class': tailwind_class}))
    company_id = forms.CharField(label='Company Identifier',
                                 widget=forms.PasswordInput(attrs={'class': tailwind_class}))

    class Meta:
        model = get_user_model()
        fields = ('email', 'password1', 'password2', 'company_id')

    # Custom validator for the company id
    def clean_company_id(self):
        company_id = self.cleaned_data['company_id']

        if not Company.objects.get(id=company_id):
            raise ValidationError("This Company ID doesn't exist")

        # Return value to use as cleaned data
        return company_id

whose validator works except of displaying the error message in case it doesn't validate.

That's my template:

<form  method="post" action=".">
            {% csrf_token %}
            <div >
                <div >{{ form.errors.email }}</div>
                <div >{{ form.errors.password2 }}</div>
                <div >{{ form.non_field_errors }}</div>
            </div>
...

CodePudding user response:

This won't work.

When you do:

SomeModel.objects.get(...)

And the object doesn't exist within the get() filtet parameters, it will raise SomeModel.DoesNotExist so try changing the .get() to a filter(...).exists() and this way you will get your custom error instead.

I'm referring to changing this line of code:

if not Company.objects.get(id=company_id):

Furthermore, if you just want to update the error message, you can specify and override the messages for each of the fields and each type or error that can happen for that field type.

See this post which was answered previously which describes how to do it:

Create Custom Error Messages with Model Forms

Also I have just noticed that in your template you don't actually display the errors for that field so please add the row to display the field errors for company id

<div >{{ form.errors.company_id }}</div>
  • Related