Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django doesn't render validation error of custom form validator

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<form class="form shadow-2xl min-w-[360px] max-w-[360px] p-4 bg-woys-purple rounded-lg text-white" method="post" action=".">
            {% csrf_token %}
            <div class="error-wrapper mb-2">
                <div class="errors text-woys-error-light text-center">{{ form.errors.email }}</div>
                <div class="errors text-woys-error-light text-center">{{ form.errors.password2 }}</div>
                <div class="errors text-woys-error-light text-center">{{ form.non_field_errors }}</div>
            </div>
...

>Solution :

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 class="errors text-woys-error-light text-center">{{ form.errors.company_id }}</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading