[Django]-How to change input fields while overriding a django save() method

5πŸ‘

βœ…

I think it’s better a pre_save signal to see if a input value is None:

from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver

class MyModel(models.Model):
    field1 = models.TextField()
    field2 = models.IntegerField()

@receiver(pre_save, sender=MyModel)
def mymodel_save_handler(sender, instance, *args, **kwargs):
     if instance.field1 is None or instance.field1 == "":
         instance.field1 = default_value

If you prefer override save method you can access to the model fields with self

 def save(self, *args, **kwargs):
        if self.username is None:
              self.username = some_default_value
        super(MyModel, self).save(*args, **kwargs)

Leave a comment