Skip to content

Instantly share code, notes, and snippets.

@bebosudo
Created September 20, 2018 22:40
Show Gist options
  • Save bebosudo/c00a8a0338bd82f2e6fdf9b7ce0744b4 to your computer and use it in GitHub Desktop.
Save bebosudo/c00a8a0338bd82f2e6fdf9b7ce0744b4 to your computer and use it in GitHub Desktop.
Setup signals in django

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment