Django: Will models.Field.validate () for all validations save a lot of coding?

I think this is all wrong , or am I really missing something ?

The Python style guide says less code is better (and I don't think that subjective ... is a fact), so consider this.

To use forms for all validations means that to write a subclass of the model field with custom validation, you need to:

  • Subclass Models. Field
  • Subclasses of forms.Field
  • Add custom validation to your forms. Subclass
  • Set the custom form field as the default form field for the custom model field.
  • Always use the django model form if you want to check

With all the validation in the model, you just need to:

  • Subclass Models. Field
  • Add custom validation to your models. Subclass subclass

Now you can use your model field in the API, which bypasses all the use of web forms, and you should still have validation at the lowest level. If you used web forms, validation will spread up.

Is there a way to do this without having to write a Django command and wait for them to fix this error?

+4
source share
2 answers

The Django development version already has this feature:

There are three steps to the model, and all three are called by full_clean() models. Most of the time, this method will be called automatically using ModelForm . You only need to call full_clean() if you plan to handle the validation errors yourself.

See documents .

eg. (as part of your model class):

 def clean(self): from django.core.exceptions import ValidationError # Don't allow draft entries to have a pub_date. if self.status == 'draft' and self.pub_date is not None: raise ValidationError('Draft entries may not have a publication date.') # Set the pub_date for published items if it hasn't been set already. if self.status == 'published' and self.pub_date is None: self.pub_date = datetime.datetime.now() 

The ModelForm validation process will call clean in your model method, for this :

As part of the validation process, ModelForm will call the clean() method of each field on your model that has a corresponding field on your form. If you exclude any model fields, validation will not be performed on those fields. Also, your model clean() method will be called before any uniqueness checks are done. See Inspecting Objects for more information on the clean() model.

+2
source

It has already been fixed and will be in Django 1.2.

+1
source

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


All Articles