0

Where should I write my save() function in Django: in models.py in a model class, or in forms.py in a form?

For example : models.py

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

    def save():
      ........ some code to override it.......

forms.py

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

Where should I override my save function?

bouteillebleu
  • 2,456
  • 23
  • 32
dilwaria
  • 33
  • 8
  • please can everyone give me a use case in which, where i shall override save in model.py or form.py , according to @Sardorbek Imomaliev, i get to know the use case and benefit of over riding save in forms.py ! – dilwaria Sep 29 '16 at 04:38
  • @Moderator Why this question got downvoted – dilwaria Sep 29 '16 at 11:38

1 Answers1

0

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

Here is default realization of ModelForm.save

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
Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63
  • thanks is helpful , first from the perspective of validation, because i need to validate. but can you give me a single use case where i shall override save function in model.py – dilwaria Sep 29 '16 at 04:35
  • @dilwaria there is almost never actual need to override model's save. Because it does many things that shouldn't be touched/changed. Usually if you want to add steps on model's save you can use [django signals](https://docs.djangoproject.com/en/1.10/topics/signals/). In my experience people override model's save only because they don't know about signals or know exactly what they are doing. – Sardorbek Imomaliev Sep 29 '16 at 04:41
  • @Sardorbrek thanks for the insight and the best practice thing! i will also go through the django signals ! – dilwaria Sep 29 '16 at 04:46