About Overriding the Save Method of the Model Form

Override the save() method of a model form to change the model's fields and attributes or call custom methods before saving to the database:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = "__all__"

    def save(self, commit=True):
        instance = super().save(commit=False)
        instance.some_flag = True
        if commit:
            instance.save()
            self.save_m2m()
        return instance

Tips and Tricks Programming Development Django 4.2 Django 3.2 Django 2.2