123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705 |
- =======
- Signals
- =======
- A list of all the signals that Django sends. All built-in signals are sent
- using the :meth:`~django.dispatch.Signal.send` method.
- .. seealso::
- See the documentation on the :doc:`signal dispatcher </topics/signals>` for
- information regarding how to register for and receive signals.
- The :doc:`authentication framework </topics/auth/index>` sends :ref:`signals when
- a user is logged in / out <topics-auth-signals>`.
- Model signals
- =============
- .. module:: django.db.models.signals
- :synopsis: Signals sent by the model system.
- The :mod:`django.db.models.signals` module defines a set of signals sent by the
- model system.
- .. warning::
- Signals can make your code harder to maintain. Consider implementing a
- helper method on a :ref:`custom manager <custom-managers>`, to
- both update your models and perform additional logic, or else
- :ref:`overriding model methods <overriding-model-methods>` before using
- model signals.
- .. warning::
- Many of these signals are sent by various model methods like
- ``__init__()`` or :meth:`~django.db.models.Model.save` that you can
- override in your own code.
- If you override these methods on your model, you must call the parent class'
- methods for these signals to be sent.
- Note also that Django stores signal handlers as weak references by default,
- so if your handler is a local function, it may be garbage collected. To
- prevent this, pass ``weak=False`` when you call the signal's :meth:`~django.dispatch.Signal.connect`.
- .. note::
- Model signals ``sender`` model can be lazily referenced when connecting a
- receiver by specifying its full application label. For example, an
- ``Question`` model defined in the ``polls`` application could be referenced
- as ``'polls.Question'``. This sort of reference can be quite handy when
- dealing with circular import dependencies and swappable models.
- ``pre_init``
- ------------
- .. attribute:: django.db.models.signals.pre_init
- :module:
- .. ^^^^^^^ this :module: hack keeps Sphinx from prepending the module.
- Whenever you instantiate a Django model, this signal is sent at the beginning
- of the model's ``__init__()`` method.
- Arguments sent with this signal:
- ``sender``
- The model class that just had an instance created.
- ``args``
- A list of positional arguments passed to ``__init__()``.
- ``kwargs``
- A dictionary of keyword arguments passed to ``__init__()``.
- For example, the :doc:`tutorial </intro/tutorial02>` has this line::
- q = Question(question_text="What's new?", pub_date=timezone.now())
- The arguments sent to a :data:`pre_init` handler would be:
- ========== ===============================================================
- Argument Value
- ========== ===============================================================
- ``sender`` ``Question`` (the class itself)
- ``args`` ``[]`` (an empty list because there were no positional
- arguments passed to ``__init__()``)
- ``kwargs`` ``{'question_text': "What's new?",``
- ``'pub_date': datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=datetime.timezone.utc)}``
- ========== ===============================================================
- ``post_init``
- -------------
- .. data:: django.db.models.signals.post_init
- :module:
- Like pre_init, but this one is sent when the ``__init__()`` method finishes.
- Arguments sent with this signal:
- ``sender``
- As above: the model class that just had an instance created.
- ``instance``
- The actual instance of the model that's just been created.
- .. note::
- :attr:`instance._state <django.db.models.Model._state>` isn't set
- before sending the ``post_init`` signal, so ``_state`` attributes
- always have their default values. For example, ``_state.db`` is
- ``None``.
- .. warning::
- For performance reasons, you shouldn't perform queries in receivers of
- ``pre_init`` or ``post_init`` signals because they would be executed for
- each instance returned during queryset iteration.
- ``pre_save``
- ------------
- .. data:: django.db.models.signals.pre_save
- :module:
- This is sent at the beginning of a model's :meth:`~django.db.models.Model.save`
- method.
- Arguments sent with this signal:
- ``sender``
- The model class.
- ``instance``
- The actual instance being saved.
- ``raw``
- A boolean; ``True`` if the model is saved exactly as presented
- (i.e. when loading a :ref:`fixture <fixtures-explanation>`). One should not
- query/modify other records in the database as the database might not be in
- a consistent state yet.
- ``using``
- The database alias being used.
- ``update_fields``
- The set of fields to update as passed to :meth:`.Model.save`, or ``None``
- if ``update_fields`` wasn't passed to ``save()``.
- ``post_save``
- -------------
- .. data:: django.db.models.signals.post_save
- :module:
- Like :data:`pre_save`, but sent at the end of the
- :meth:`~django.db.models.Model.save` method.
- Arguments sent with this signal:
- ``sender``
- The model class.
- ``instance``
- The actual instance being saved.
- ``created``
- A boolean; ``True`` if a new record was created.
- ``raw``
- A boolean; ``True`` if the model is saved exactly as presented
- (i.e. when loading a :ref:`fixture <fixtures-explanation>`). One should not
- query/modify other records in the database as the database might not be in
- a consistent state yet.
- ``using``
- The database alias being used.
- ``update_fields``
- The set of fields to update as passed to :meth:`.Model.save`, or ``None``
- if ``update_fields`` wasn't passed to ``save()``.
- ``pre_delete``
- --------------
- .. data:: django.db.models.signals.pre_delete
- :module:
- Sent at the beginning of a model's :meth:`~django.db.models.Model.delete`
- method and a queryset's :meth:`~django.db.models.query.QuerySet.delete` method.
- Arguments sent with this signal:
- ``sender``
- The model class.
- ``instance``
- The actual instance being deleted.
- ``using``
- The database alias being used.
- ``origin``
- The origin of the deletion being the instance of a ``Model`` or
- ``QuerySet`` class.
- ``post_delete``
- ---------------
- .. data:: django.db.models.signals.post_delete
- :module:
- Like :data:`pre_delete`, but sent at the end of a model's
- :meth:`~django.db.models.Model.delete` method and a queryset's
- :meth:`~django.db.models.query.QuerySet.delete` method.
- Arguments sent with this signal:
- ``sender``
- The model class.
- ``instance``
- The actual instance being deleted.
- Note that the object will no longer be in the database, so be very
- careful what you do with this instance.
- ``using``
- The database alias being used.
- ``origin``
- The origin of the deletion being the instance of a ``Model`` or
- ``QuerySet`` class.
- ``m2m_changed``
- ---------------
- .. data:: django.db.models.signals.m2m_changed
- :module:
- Sent when a :class:`~django.db.models.ManyToManyField` is changed on a model
- instance. Strictly speaking, this is not a model signal since it is sent by the
- :class:`~django.db.models.ManyToManyField`, but since it complements the
- :data:`pre_save`/:data:`post_save` and :data:`pre_delete`/:data:`post_delete`
- when it comes to tracking changes to models, it is included here.
- Arguments sent with this signal:
- ``sender``
- The intermediate model class describing the
- :class:`~django.db.models.ManyToManyField`. This class is automatically
- created when a many-to-many field is defined; you can access it using the
- ``through`` attribute on the many-to-many field.
- ``instance``
- The instance whose many-to-many relation is updated. This can be an
- instance of the ``sender``, or of the class the
- :class:`~django.db.models.ManyToManyField` is related to.
- ``action``
- A string indicating the type of update that is done on the relation.
- This can be one of the following:
- ``"pre_add"``
- Sent *before* one or more objects are added to the relation.
- ``"post_add"``
- Sent *after* one or more objects are added to the relation.
- ``"pre_remove"``
- Sent *before* one or more objects are removed from the relation.
- ``"post_remove"``
- Sent *after* one or more objects are removed from the relation.
- ``"pre_clear"``
- Sent *before* the relation is cleared.
- ``"post_clear"``
- Sent *after* the relation is cleared.
- ``reverse``
- Indicates which side of the relation is updated (i.e., if it is the
- forward or reverse relation that is being modified).
- ``model``
- The class of the objects that are added to, removed from or cleared
- from the relation.
- ``pk_set``
- For the ``pre_add`` and ``post_add`` actions, this is a set of primary key
- values that will be, or have been, added to the relation. This may be a
- subset of the values submitted to be added, since inserts must filter
- existing values in order to avoid a database ``IntegrityError``.
- For the ``pre_remove`` and ``post_remove`` actions, this is a set of
- primary key values that was submitted to be removed from the relation. This
- is not dependent on whether the values actually will be, or have been,
- removed. In particular, non-existent values may be submitted, and will
- appear in ``pk_set``, even though they have no effect on the database.
- For the ``pre_clear`` and ``post_clear`` actions, this is ``None``.
- ``using``
- The database alias being used.
- For example, if a ``Pizza`` can have multiple ``Topping`` objects, modeled
- like this::
- class Topping(models.Model):
- # ...
- pass
- class Pizza(models.Model):
- # ...
- toppings = models.ManyToManyField(Topping)
- If we connected a handler like this::
- from django.db.models.signals import m2m_changed
- def toppings_changed(sender, **kwargs):
- # Do something
- pass
- m2m_changed.connect(toppings_changed, sender=Pizza.toppings.through)
- and then did something like this:
- .. code-block:: pycon
- >>> p = Pizza.objects.create(...)
- >>> t = Topping.objects.create(...)
- >>> p.toppings.add(t)
- the arguments sent to a :data:`m2m_changed` handler (``toppings_changed`` in
- the example above) would be:
- ============== ============================================================
- Argument Value
- ============== ============================================================
- ``sender`` ``Pizza.toppings.through`` (the intermediate m2m class)
- ``instance`` ``p`` (the ``Pizza`` instance being modified)
- ``action`` ``"pre_add"`` (followed by a separate signal with ``"post_add"``)
- ``reverse`` ``False`` (``Pizza`` contains the
- :class:`~django.db.models.ManyToManyField`, so this call
- modifies the forward relation)
- ``model`` ``Topping`` (the class of the objects added to the
- ``Pizza``)
- ``pk_set`` ``{t.id}`` (since only ``Topping t`` was added to the relation)
- ``using`` ``"default"`` (since the default router sends writes here)
- ============== ============================================================
- And if we would then do something like this:
- .. code-block:: pycon
- >>> t.pizza_set.remove(p)
- the arguments sent to a :data:`m2m_changed` handler would be:
- ============== ============================================================
- Argument Value
- ============== ============================================================
- ``sender`` ``Pizza.toppings.through`` (the intermediate m2m class)
- ``instance`` ``t`` (the ``Topping`` instance being modified)
- ``action`` ``"pre_remove"`` (followed by a separate signal with ``"post_remove"``)
- ``reverse`` ``True`` (``Pizza`` contains the
- :class:`~django.db.models.ManyToManyField`, so this call
- modifies the reverse relation)
- ``model`` ``Pizza`` (the class of the objects removed from the
- ``Topping``)
- ``pk_set`` ``{p.id}`` (since only ``Pizza p`` was removed from the
- relation)
- ``using`` ``"default"`` (since the default router sends writes here)
- ============== ============================================================
- ``class_prepared``
- ------------------
- .. data:: django.db.models.signals.class_prepared
- :module:
- Sent whenever a model class has been "prepared" -- that is, once a model has
- been defined and registered with Django's model system. Django uses this
- signal internally; it's not generally used in third-party applications.
- Since this signal is sent during the app registry population process, and
- :meth:`AppConfig.ready() <django.apps.AppConfig.ready>` runs after the app
- registry is fully populated, receivers cannot be connected in that method.
- One possibility is to connect them ``AppConfig.__init__()`` instead, taking
- care not to import models or trigger calls to the app registry.
- Arguments that are sent with this signal:
- ``sender``
- The model class which was just prepared.
- Management signals
- ==================
- Signals sent by :doc:`django-admin </ref/django-admin>`.
- ``pre_migrate``
- ---------------
- .. data:: django.db.models.signals.pre_migrate
- :module:
- Sent by the :djadmin:`migrate` command before it starts to install an
- application. It's not emitted for applications that lack a ``models`` module.
- Arguments sent with this signal:
- ``sender``
- An :class:`~django.apps.AppConfig` instance for the application about to
- be migrated/synced.
- ``app_config``
- Same as ``sender``.
- ``verbosity``
- Indicates how much information ``manage.py`` is printing on screen. See
- the :option:`--verbosity` flag for details.
- Functions which listen for :data:`pre_migrate` should adjust what they
- output to the screen based on the value of this argument.
- ``interactive``
- If ``interactive`` is ``True``, it's safe to prompt the user to input
- things on the command line. If ``interactive`` is ``False``, functions
- which listen for this signal should not try to prompt for anything.
- For example, the :mod:`django.contrib.auth` app only prompts to create a
- superuser when ``interactive`` is ``True``.
- ``stdout``
- A stream-like object where verbose output should be redirected.
- ``using``
- The alias of database on which a command will operate.
- ``plan``
- The migration plan that is going to be used for the migration run. While
- the plan is not public API, this allows for the rare cases when it is
- necessary to know the plan. A plan is a list of 2-tuples with the first
- item being the instance of a migration class and the second item showing
- if the migration was rolled back (``True``) or applied (``False``).
- ``apps``
- An instance of :data:`Apps <django.apps>` containing the state of the
- project before the migration run. It should be used instead of the global
- :attr:`apps <django.apps.apps>` registry to retrieve the models you
- want to perform operations on.
- ``post_migrate``
- ----------------
- .. data:: django.db.models.signals.post_migrate
- :module:
- Sent at the end of the :djadmin:`migrate` (even if no migrations are run) and
- :djadmin:`flush` commands. It's not emitted for applications that lack a
- ``models`` module.
- Handlers of this signal must not perform database schema alterations as doing
- so may cause the :djadmin:`flush` command to fail if it runs during the
- :djadmin:`migrate` command.
- Arguments sent with this signal:
- ``sender``
- An :class:`~django.apps.AppConfig` instance for the application that was
- just installed.
- ``app_config``
- Same as ``sender``.
- ``verbosity``
- Indicates how much information ``manage.py`` is printing on screen. See
- the :option:`--verbosity` flag for details.
- Functions which listen for :data:`post_migrate` should adjust what they
- output to the screen based on the value of this argument.
- ``interactive``
- If ``interactive`` is ``True``, it's safe to prompt the user to input
- things on the command line. If ``interactive`` is ``False``, functions
- which listen for this signal should not try to prompt for anything.
- For example, the :mod:`django.contrib.auth` app only prompts to create a
- superuser when ``interactive`` is ``True``.
- ``stdout``
- A stream-like object where verbose output should be redirected.
- ``using``
- The database alias used for synchronization. Defaults to the ``default``
- database.
- ``plan``
- The migration plan that was used for the migration run. While the plan is
- not public API, this allows for the rare cases when it is necessary to
- know the plan. A plan is a list of 2-tuples with the first item being
- the instance of a migration class and the second item showing if the
- migration was rolled back (``True``) or applied (``False``).
- ``apps``
- An instance of :data:`Apps <django.apps.apps>` containing the state of the
- project after the migration run. It should be used instead of the global
- :attr:`apps <django.apps.apps>` registry to retrieve the models you
- want to perform operations on.
- For example, you could register a callback in an
- :class:`~django.apps.AppConfig` like this::
- from django.apps import AppConfig
- from django.db.models.signals import post_migrate
- def my_callback(sender, **kwargs):
- # Your specific logic here
- pass
- class MyAppConfig(AppConfig):
- ...
- def ready(self):
- post_migrate.connect(my_callback, sender=self)
- .. note::
- If you provide an :class:`~django.apps.AppConfig` instance as the sender
- argument, please ensure that the signal is registered in
- :meth:`~django.apps.AppConfig.ready`. ``AppConfig``\s are recreated for
- tests that run with a modified set of :setting:`INSTALLED_APPS` (such as
- when settings are overridden) and such signals should be connected for each
- new ``AppConfig`` instance.
- Request/response signals
- ========================
- .. module:: django.core.signals
- :synopsis: Core signals sent by the request/response system.
- Signals sent by the core framework when processing a request.
- .. warning::
- Signals can make your code harder to maintain. Consider :doc:`using a
- middleware </topics/http/middleware>` before using request/response
- signals.
- ``request_started``
- -------------------
- .. data:: django.core.signals.request_started
- :module:
- Sent when Django begins processing an HTTP request.
- Arguments sent with this signal:
- ``sender``
- The handler class -- e.g. ``django.core.handlers.wsgi.WsgiHandler`` -- that
- handled the request.
- ``environ``
- The ``environ`` dictionary provided to the request.
- ``request_finished``
- --------------------
- .. data:: django.core.signals.request_finished
- :module:
- Sent when Django finishes delivering an HTTP response to the client.
- Arguments sent with this signal:
- ``sender``
- The handler class, as above.
- ``got_request_exception``
- -------------------------
- .. data:: django.core.signals.got_request_exception
- :module:
- This signal is sent whenever Django encounters an exception while processing an incoming HTTP request.
- Arguments sent with this signal:
- ``sender``
- Unused (always ``None``).
- ``request``
- The :class:`~django.http.HttpRequest` object.
- Test signals
- ============
- .. module:: django.test.signals
- :synopsis: Signals sent during testing.
- Signals only sent when :ref:`running tests <running-tests>`.
- ``setting_changed``
- -------------------
- .. data:: django.test.signals.setting_changed
- :module:
- This signal is sent when the value of a setting is changed through the
- ``django.test.TestCase.settings()`` context manager or the
- :func:`django.test.override_settings` decorator/context manager.
- It's actually sent twice: when the new value is applied ("setup") and when the
- original value is restored ("teardown"). Use the ``enter`` argument to
- distinguish between the two.
- You can also import this signal from ``django.core.signals`` to avoid importing
- from ``django.test`` in non-test situations.
- Arguments sent with this signal:
- ``sender``
- The settings handler.
- ``setting``
- The name of the setting.
- ``value``
- The value of the setting after the change. For settings that initially
- don't exist, in the "teardown" phase, ``value`` is ``None``.
- ``enter``
- A boolean; ``True`` if the setting is applied, ``False`` if restored.
- ``template_rendered``
- ---------------------
- .. data:: django.test.signals.template_rendered
- :module:
- Sent when the test system renders a template. This signal is not emitted during
- normal operation of a Django server -- it is only available during testing.
- Arguments sent with this signal:
- ``sender``
- The :class:`~django.template.Template` object which was rendered.
- ``template``
- Same as sender
- ``context``
- The :class:`~django.template.Context` with which the template was
- rendered.
- Database Wrappers
- =================
- .. module:: django.db.backends
- :synopsis: Core signals sent by the database wrapper.
- Signals sent by the database wrapper when a database connection is
- initiated.
- ``connection_created``
- ----------------------
- .. data:: django.db.backends.signals.connection_created
- :module:
- Sent when the database wrapper makes the initial connection to the
- database. This is particularly useful if you'd like to send any post
- connection commands to the SQL backend.
- Arguments sent with this signal:
- ``sender``
- The database wrapper class -- i.e.
- ``django.db.backends.postgresql.DatabaseWrapper`` or
- ``django.db.backends.mysql.DatabaseWrapper``, etc.
- ``connection``
- The database connection that was opened. This can be used in a
- multiple-database configuration to differentiate connection signals
- from different databases.
|