How can I know in MyForm.clean() whether the data is new, or if already saved data is being modifed?
What should is_this_new_data() look like in the following code?
class MyForm(forms.ModelForm):
def clean(self):
cleaned_data = self.cleaned_data
if is_this_new_data(self):
# perform some checks if this is new data
else:
# do nothing if this is data being modifed
return cleaned_data
Use the has_changed() method on your Form when you need to check if the form data has been changed from the initial data. has_changed() will be True if the data from request.
Since Django 1.8 released, you can use from_db classmethod to cache old value of remote_image. Then in save method you can compare old and new value of field to check if the value has changed. @classmethod def from_db(cls, db, field_names, values): new = super(Alias, cls).
The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute. Let's see an example that takes user input and validate input as well.
cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. form. data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With