Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 286
Helgi Borg Avatar asked Nov 03 '11 14:11

Helgi Borg


People also ask

What method can be used to check if form data has been changed when using a form instance?

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.

When saving How can you check if a field has changed Django?

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).

How do I check if a form is valid in Django?

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.

What does cleaned data do in Django?

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).


2 Answers

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.

like image 58
Chris Pratt Avatar answered Sep 19 '22 15:09

Chris Pratt


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
like image 42
Alasdair Avatar answered Sep 18 '22 15:09

Alasdair