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
Here is an app that gives you access to previous and current value of a field right before model will be saved: django-smartfields
Here is how this problem can be solved in a nice declarative may:
from django.db import models
from smartfields import fields, processors
from smartfields.dependencies import Dependency
class ConditionalProcessor(processors.BaseProcessor):
def process(self, value, stashed_value=None, **kwargs):
if value != stashed_value:
# do any necessary modifications to new value
value = ...
return value
class MyModel(models.Model):
my_field = fields.CharField(max_length=10, dependencies=[
Dependency(processor=ConditionalProcessor())
])
Moreover, this processor will be invoked, only in case that field's value was replaced
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