Where to write the save function in Django?
<p>Where to write my save function in django whether in models.py in a class model or in forms.py in form ?</p>

<p>For example :
models.py </p>

<pre><code>class Customer(models.Model):
    name = models.CharField(max_length=200)
    created_by = models.ForeignKey(User)

    def save():
      ........ some code to override it.......
</code></pre>

<p>forms.py</p>

<pre><code>class  Addcustomer(forms.ModelForm):
   class Meta:
       model = Customer
       fields = ('name',)
   def save():
     ........code to override it.... 
</code></pre>

<p>where shall i override my save function </p>

<p>It really depends on what you are trying to achieve. Default realization of <code>ModelForm</code>'s save calls <code>Model</code>'s save. But it is usually better to override it on <code>form</code> because it also runs validation. So if you are already using form I would suggest overriding <code>ModelForm.save</code>. And by overriding I mean extending using <code>super</code></p>

<p>Here is default realization of <code>ModelForm.save</code></p>

<pre><code>def save(self, commit=True):
    """
    Save this form's self.instance object if commit=True. Otherwise, add
    a save_m2m() method to the form which can be called after the instance
    is saved manually at a later time. Return the model instance.
    """
    if self.errors: # there validation is done
        raise ValueError(
            "The %s could not be %s because the data didn't validate." % (
                self.instance._meta.object_name,
                'created' if self.instance._state.adding else 'changed',
            )
        )
    if commit:
        # If committing, save the instance and the m2m data immediately.
        self.instance.save()
        self._save_m2m()
    else:
        # If not committing, add a method to the form to allow deferred
        # saving of m2m data.
        self.save_m2m = self._save_m2m
    return self.instance

save.alters_data = True
</code></pre>

python django django-models django-forms