Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - How to specify which field a validation fails on?

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.

like image 927
Greg Avatar asked Jun 13 '11 17:06

Greg


People also ask

How do I display validation error in Django?

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.

How do you remove this field is required Django?

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.

How can you validate Django model fields?

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)

What can be used to validate all model fields if any field is to be exempted from validation provide it in the exclude parameter?

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.


1 Answers

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!",]}) 
like image 92
Greg Avatar answered Sep 30 '22 13:09

Greg