[Fixed]-Django – how to know in clean method if the form-data is new or if old data is being changed

28👍

Check self.cleaned_data['some_field'] against self.instance.some_field.

A quick way to check if the object is new is to see if self.instance.pk has a value. It will be None unless the object already exists.

7👍

In the clean you can access the changed_data attribute, which is a list of the names of the fields which have changed.

def clean(self):
    cleaned_data = self.cleaned_data:
    for field_name in self.changed_data:
        # loop through the fields which have changed
        print "field %s has changed. new value %s" % (field_name, cleaned_data[field_name])
        do_something()
    return cleaned_data

Leave a comment