tyebillion tyebillion - 1 month ago 6
Python Question

How to execute code on save in Django User model?

I would like to run some code specifically when the is_active field is changed for a Django User, similar to how the save method works for other models:

class Foo(models.Model):
...
def save(self, *args, **kwargs):
if self.pk is not None:
orig = Foo.objects.get(pk=self.pk)
if orig.is_active != self.is_active:
# code goes here


Can this be done through another model that is in one to one relation with the User model? Something like:

class Bar(models.Model):
owner = models.OneToOneField(User, on_save=?)
...


I guess I could duplicate the is_active field on the related model and then set the is_active field on the User when saving the related model. But this seems like a bit of a messy solution.

Answer

You're looking for this Signal

from django.db.models.signals import pre_save
from django.contrib.auth.models import User

def do_your_thing(sender, instance, **kwargs):
    # Do something
    print(instance)

pre_save.connect(do_your_thing, sender=User)
Comments