Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django field validation in Model and in Admin?

I want to define my own validation routine for a particular field of a Django model. I want the error message to be displayed in the admin form but I also want the same validation to take place if the entity is saved by own python code. Is there a way to do this without breaking the DRY principle?

like image 810
Al Bundy Avatar asked Sep 26 '12 19:09

Al Bundy


People also ask

How do I validate two fields in Django?

They go into a special “field” (called all), which you can access via the non_field_errors() method if you need to. If you want to attach errors to a specific field in the form, you need to call add_error(). So from Django documentation you can use add_error() to do what you want to achieve.

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.

How do I increase validation error in Django admin?

In django 1.2, model validation has been added. You can now add a "clean" method to your models which raise ValidationError exceptions, and it will be called automatically when using the django admin. The clean() method is called when using the django admin, but NOT called on save() .


1 Answers

If you want to validate an individual field, you can write a validator and add it to your model field.

The validator will be run for the field whenever the model's full_clean method is called. It will be run whenever a model form is validated (including in the Django admin), but it will not automatically run when the model instance is saved - you must call full_clean manually in python code.

m = MyModel(x=20)
m.full_clean() # may raise ValidationError
m.save()

If you wanted to force the validator to run whenever the model is saved, then you could override the save method and call full_clean there. Note that this would cause the validation to run twice when using model forms and the django admin.

like image 114
Alasdair Avatar answered Sep 28 '22 13:09

Alasdair