How to determine if a field has changed in a Django modelform

Viewed 26668

I was surprised that this was difficult to do. However I came up with this, which seems to work at least for my simple case. Can anyone recommend a better approach?

def field_changed(self, fieldname):
    """Tests if the value of the field changed from the original data"""
    orig_value = self.fields[fieldname].initial or getattr(self.instance, field, None)
    orig_value = getattr(orig_value, 'pk', orig_value)
    if type(orig_value) is bool:
        # because None and False can be interchangeable
        return bool(self.data.get(fieldname)) != bool(orig_value)
    else:
        return unicode(self.data.get(fieldname)) != unicode(orig_value)
4 Answers

Extending on Airs's answer, for multiple fields:

In a scenario where you'd like to track changes for a list of fields ['field_a', 'field_b', 'field_c']


If you'd like to check if any of those fields has changed:

any(x in myforminstance.changed_data for x in ['field_a', 'field_b', 'field_c'])

If you'd like to check if all of those fields have changed:

all(x in myforminstance.changed_data for x in ['field_a', 'field_b', 'field_c'])
Related