Vassily
Vassily

Reputation: 5438

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?

Upvotes: 3

Views: 1115

Answers (2)

Ashok Kmr
Ashok Kmr

Reputation: 49

write validation in clean() method or clean_<fieldname>()

from django.core.exceptions import ValidationError
class model
   ..........
   ..........
   def clean(self):
        if not self.author.is_staff:
           raise ValidationError(f"{self.author} is not a staff or admin ,don't have permission to write post")

Upvotes: 0

gasman
gasman

Reputation: 25317

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.

Upvotes: 5

Related Questions