Is this the way to validate Django model fields?

前端 未结 3 1920
时光说笑
时光说笑 2020-11-29 07:24

As I understand it, when one creates a Django application, data is validated by the form before it\'s inserted into a model instance which is then written to the database.

3条回答
  •  再見小時候
    2020-11-29 08:02

    Capturing the pre-save signals on on my models ensured clean will be called automatically.

    from django.db.models.signals import pre_save
    
    def validate_model(sender, **kwargs):
        if 'raw' in kwargs and not kwargs['raw']:
            kwargs['instance'].full_clean()
    
    pre_save.connect(validate_model, dispatch_uid='validate_models')
    

提交回复
热议问题