Django Signals is a feature in Django, a popular high-level Python Web framework, which allows certain kinds of events to be announced within a Django application. These signals can be listened to and acted upon by other parts of the application, hence acting as a messaging system within the application. This system is hugely valuable because it allows decoupling of application components. Decoupling essentially means that different parts of your project can function independently without knowing about, or depending upon, the inner workings of other parts.
Django signals are defined in the official Django documentation as a certain set of named messages that the Django framework may send at various points in the execution of an application. These messages, or “signals,” are dispatched when actions or events of interest happen, such as the saving or deletion of a Django model instance.
For example, consider an e-commerce application. You can create a signal to send a transaction email to the customer whenever a purchase is complete. In this scenario, the “confirmation of purchase” event triggers the signal, which then triggers the sending of an email. This shows how signals serve as a useful mechanism for allowing decoupled applications to connect to each other.
There are two types of signals in Django: built-in signals and custom signals. Built-in signals are automatically sent by Django on some actions, such as when a model’s `save()` or `delete()` method is called. These signals include pre_save, post_save, pre_delete, post_delete, and others. On the other hand, developers can also define their own custom signals.
Creating signals in Django involves defining a signal, connecting it with receivers (functions that would get called when the signal is sent), and finally sending the signal in the appropriate place in the code. Receivers can be connected to a signal, so they are called when the signal is sent. Each receiver is a Python function that gets called when its signal is dispatched.
It is important to note that signals are not always the best approach due to their unpredictability and the lack of strict sequencing, and are notably not suitable for every kind of operation. The official Django documentation even contains a section titled ‘Avoiding Signals’ urging developers to use signals judiciously and to avoid them wherever simpler options like model methods, managers, or query sets can be used.
Sources:
1. Django official documentation: https://docs.djangoproject.com/en/3.2/topics/signals/
2. ‘Django for Professionals: Production websites with Python & Django’ by William S. Vincent
3. Django Best Practices: Signals: http://lincolnloop.com/django-best-practices/other-code/signals.html
4. ‘Two Scoops of Django: Best Practices for Django 1.6’ by Audre Roy Greenfeld and Daniel Roy Greenfeld.