How to execute code on save in Django User model?
<p>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:</p>

<pre><code>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
</code></pre>

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

<pre><code>class Bar(models.Model):
    owner = models.OneToOneField(User, on_save=?)
    ...
</code></pre>

<p>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.</p>

<p>You're looking for this <a href="https://docs.djangoproject.com/en/1.10/ref/signals/#django.db.models.signals.pre_save" rel="nofollow">Signal</a></p>

<pre><code>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)
</code></pre>

python django