Daniele Duboin
Daniele Duboin

Reputation: 129

Call a function after saving a model

I'm working on a Django application connected to a LDAP server. Here's the trick i'm trying to do.

I have a model called system containing some information about computers. When i add a new system, the model generates a unique UUID, like and AutoField. The point is that this parameter is generated when saving, and only the first time.
After saved, i need a function to keep that UUID and create a new object on my LDAP.
Since i didn't know a lot about signals, i tried overriding the model save function in this way:

def save(self):

        # import needed modules
        import ldap
        import ldap.modlist as modlist

        [--OPERATIONS ON THE LDAP--]

        super(System, self).save()

In this way, if i modify an existing system all work as should, because its UUID has been generated already. But if i try adding a new system i find the error UUID is None, and i can't work with an empty variable on LDAP (also it would be useless, don't u think so?)

It seems i need to call the function that work on LDAP after the system is saved, and so after an UUID has been generated. I tried to unserstand how to create a post_save function but i couldn't get it.
How can i do that?

Thanks

Upvotes: 3

Views: 1764

Answers (2)

petkostas
petkostas

Reputation: 7460

As you stated on your own, you do need signals, it will allow your code to stay more clean and seperate logic between parts.

The usual approach is to place signals just at the end of your models file:

# Signals
from django.dispatch import receiver

@receiver(models.signals.post_save, sender=YourModel)
def do_something(sender, instance, created, **kwargs):

    ....

On the above example we connect the post_save signal with the do_something function, this is performed through the decorator @receiver, sender of the decorator points to your Model Class. Inside your function you have instance which holds the current instance of the model and the created flag which allows you to determine if this is a new record or an old (if the Model is being updated).

Upvotes: 1

Björn Kristinsson
Björn Kristinsson

Reputation: 624

Signals would be excellent for something like this, but moving the line super(System, self).save() to the top of the save method might work as well. That means you first save the instance, before passing the saved object to the LDAP.

Upvotes: 0

Related Questions