How to restrict a custom validator to only pushing errors to field.errors and not django messages?

74 Views Asked by At

I am using a custom validator on a model field.

Model field:

html_content = models.TextField(blank=True,
                                verbose_name=_("HTML content"),
                                validators=[validate_template_syntax])

Validator:

def validate_template_syntax(source):
    try:
        Template(source)
    except (TemplateSyntaxError, TemplateDoesNotExist) as err:
        raise ValidationError(str(err))

However, when the validator error is triggered, it pushes the error to both the django messages framework (messages) and field.errors, so in a template if I am rendering other messages alongside a form the error is displayed twice.

How do I restrict the validator to only pushing the error to the field errors context?

1

There are 1 best solutions below

0
On

As @Melyvn states, check your code! I had overwritten form_invalid.

def form_invalid(self, form):
    """If the form is invalid, render the invalid form."""
    messages.error(
         self.request,
         form.errors,
         extra_tags='safe'
    )
    return self.render_to_response(self.get_context_data(form=form))