django - comparing old and new field value before saving

前端 未结 8 721
温柔的废话
温柔的废话 2020-12-12 20:40

I have a django model, and I need to compare old and new values of field BEFORE saving.

I\'ve tried the save() inheritence, and pre_save signal. It was triggered cor

8条回答
  •  醉梦人生
    2020-12-12 21:10

    I agree with Sahil that it is better and easier to do this with ModelForm. However, you would customize the ModelForm's clean method and perform validation there. In my case, I wanted to prevent updates to a model's instance if a field on the model is set.

    My code looked like this:

    from django.forms import ModelForm
    
    class ExampleForm(ModelForm):
        def clean(self):
            cleaned_data = super(ExampleForm, self).clean()
            if self.instance.field:
                raise Exception
            return cleaned_data
    

提交回复
热议问题