Inside your application directory, create a file your_app/signals.py
.
The default project and app creator should have created a file your_app/apps.py
.
Inside the class used for your app, add the ready
method:
class YourAppConfig(AppConfig):
name = 'your_app'
def ready(self):
from . import signals
An example of signal can be:
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django.utils import timezone
from . import models
@receiver(pre_delete, sender=models.Person)
def copy_person_data_before_deleting(sender, **kwargs):
"""When deleting a Person, at least a copy of its details are kept for accounting."""
instance = kwargs["instance"]
for pc in instance.personcosts_set.all():
pc.child_copy = pc.person.short_str()
pc.date_to = timezone.now().today()
pc.save()
Refer to the signals documentation for more details.