[ACCEPTED]-Return error message after saving a model with custom save() method on Django Admin-django-admin

Accepted answer
Score: 12

I would recommend validating in both clean() and 14 save(). The former will give you a nice error 13 message and workflow in the admin, while 12 the latter will make sure that save() itself gives 11 an error message regardless of how you're 10 creating the instance.

First the validation:

class Subscriber(models.Model):

    def clean(self)
        if not self.pk:
            if not Pool.objects.annotate(num_subscribers=Count('subscriber'))
                raise ValidationError('The pools are all full.')

This 9 will be called automatically from the admin 8 (see the documentation on ModelForm validation). Alternatively 7 - if you're not cleaning things outside 6 of ModelForm validation - you could supply this logic 5 in the form's clean() method.

Then do the same thing 4 in the save() method.

    def save(self, *args, **kwargs):
        if not self.pk:
                self.pool = Pool.objects.annotate(num_subscribers=Count('subscriber'))
                super(Subscriber, self).save(*args, **kwargs)
            except IndexError:
                raise ValidationError(..)

You could instead call self.full_clean() inside 3 save() to do the validation, but this version 2 seems more straightforward (and is definitely 1 more efficient).

More Related questions