djangovalidationwagtail

Wagtail not shows ValidationError correctly


I have XOR validation of wagtail.core.models.Page descedant:

def save(self, *args, **kwargs):
    if self.video_playlist is not None and self.gallery is not None:
        raise ValidationError(_("Only gallery or only video playlist must be filled"))
    elif self.video_playlist is None and self.gallery is None:
        raise ValidationError(_("Only gallery or only video playlist must be filled"))
    super(OkoPage, self).save(*args, **kwargs)

But instead of red color highlighting wagtail returns 400 error.enter image description here How to do it right?


Solution

  • You should perform this validation in a clean method on the model, not within save. This way, the ValidationError will be caught by Django's form handling logic and converted into an error message on the form.

    The save method is only called after the form handling has been completed, so throwing a ValidationError at that point is too late for it to be handled nicely.