pythondjangodjango-formsdjango-admindjango-validation

How to detect if obj is being added or edited inside ModelForm.clean?


I want to validate user submitted data differently whether the user is adding a new object or changing an existing one. There isn't an attribute of the model other than the id that I could check on the db if the object already exist (if it exist on the db, it's being added). In other methods, like save_model, a add parameter is passed, so you can check it, but in modelform.clean there is no such parameter. How to do that verification inside modelform.clean?

MyModelForm(forms.ModelForm):
    def clean(self):
        if add :
            validation_A()
        else:
            validantion_B()

Solution

  • An object that does not exists at the database level has an id (well perhaps it is better to use pk) that is None (since the id is determined upon an insert in the database, Django does not assign that id).

    So we can check if the self.instance.pk is None:

    MyModelForm(forms.ModelForm):
    
        def clean(self):
            if self.instance.pk is None:  # add
                validation_A()
            else:                         # edit
                validantion_B()

    Of course the above method can be "spoofed" in the sense that before you pass the object in the creation, you can set the id to None, but the Model.save(..) object uses this fact as well to decide wether to perform an INSERT INTO, or an UPDATE.