Custom ModelField validation in Django

my model looks like this:

class MyModel(models.Model): field1 = models.FloatField(default=0) field2 = models.FloatField(default=0) 

Here's how he behaves:

 >>> m = MyModel() >>> m.full_clean() >>> m = MyModel(field1=8.9) >>> m.full_clean() >>> m = MyModel(field1='') >>> m.full_clean() ValidationError: {'field1': [u'This value must be a float.'], ... 

I want him to accept empty strings and use it 0. I also want him to accept values ​​like "5:56" and whether he uses "5.93333". (I already have a function that can do this)

I am currently working with a custom form field (and this is ugly as a sin), but I want to move all this to use model validation. What is the best way to do this?

+1
source share
1 answer

Make a clean_field1 function in your form and check it there. Throw a validation error if it does not match, and reformat and return the "correct" value, if any. Example:

http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute

Update:

The question has been clarified: the user needs a Model field that does this.

Override FloatField and get_prep_value and to_python inside:

 class MagicalFloatField(FloatField): def to_python( self, value_from_db ): ... return what_should_go_into_model_field_value def get_prep_value( self, value_from_field ): ... return what_should_go_into_db 

So you can do "5:26" ↔ "5.26". Then use your field in your model:

 class MagicalModel(Model): foo = MagicalFloatField() 

Link:

http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#django.db.models.to_python

Also, for an example of what he expects and how to increase validation errors, see what you subclass β€” look at FloatField in site-packages/django/db/models/fields/__init__.py

+1
source

Source: https://habr.com/ru/post/1369324/


All Articles