简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM