I have this model I'm showing in the admin page:
class Dog(models.Model): bark_volume = models.DecimalField(... unladen_speed = models.DecimalField(... def clean(self): if self.bark_volume < 5: raise ValidationError("must be louder!")
As you can see I put a validation on the model. But what I want to happen is for the admin page to show the error next to the bark_volume field instead of a general error like it is now. Is there a way to specify which field the validation is failing on?
Much thanks in advance.
To display the form errors, you use form. is_valid() to make sure that it passes validation. Django says the following for custom validations: Note that any errors raised by your Form.
If yes try to disable this behavior, set the novalidate attribute on the form tag As <form action="{% url 'new_page' %}", method="POST" novalidate> in your html file. At you model, the setting title/content = CharField(null=True, blank=True) doesn´t work? At your model-form have you tried setting title/content = forms.
to_python() method of the models. Field subclass (obviously for that to work you must write custom fields). Possible use cases: when it is absolutely neccessary to ensure, that an empty string doesn't get written into the database (blank=False keyword argument doesn't work here, it is for form validation only)
clean_fields() method documentation: This method will validate all fields on your model. The optional exclude argument lets you provide a list of field names to exclude from validation. It will raise a ValidationError if any fields fail validation.
OK, I figured it out from this answer.
You have to do something like this:
class Dog(models.Model): bark_volume = models.DecimalField(... unladen_speed = models.DecimalField(... def clean_fields(self): if self.bark_volume < 5: raise ValidationError({'bark_volume': ["Must be louder!",]})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With