2
0

signals.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. =======
  2. Signals
  3. =======
  4. A list of all the signals that Django sends. All built-in signals are sent
  5. using the :meth:`~django.dispatch.Signal.send` method.
  6. .. seealso::
  7. See the documentation on the :doc:`signal dispatcher </topics/signals>` for
  8. information regarding how to register for and receive signals.
  9. The :doc:`authentication framework </topics/auth/index>` sends :ref:`signals when
  10. a user is logged in / out <topics-auth-signals>`.
  11. Model signals
  12. =============
  13. .. module:: django.db.models.signals
  14. :synopsis: Signals sent by the model system.
  15. The :mod:`django.db.models.signals` module defines a set of signals sent by the
  16. model system.
  17. .. warning::
  18. Signals can make your code harder to maintain. Consider implementing a
  19. helper method on a :ref:`custom manager <custom-managers>`, to
  20. both update your models and perform additional logic, or else
  21. :ref:`overriding model methods <overriding-model-methods>` before using
  22. model signals.
  23. .. warning::
  24. Many of these signals are sent by various model methods like
  25. ``__init__()`` or :meth:`~django.db.models.Model.save` that you can
  26. override in your own code.
  27. If you override these methods on your model, you must call the parent class'
  28. methods for these signals to be sent.
  29. Note also that Django stores signal handlers as weak references by default,
  30. so if your handler is a local function, it may be garbage collected. To
  31. prevent this, pass ``weak=False`` when you call the signal's :meth:`~django.dispatch.Signal.connect`.
  32. .. note::
  33. Model signals ``sender`` model can be lazily referenced when connecting a
  34. receiver by specifying its full application label. For example, an
  35. ``Question`` model defined in the ``polls`` application could be referenced
  36. as ``'polls.Question'``. This sort of reference can be quite handy when
  37. dealing with circular import dependencies and swappable models.
  38. ``pre_init``
  39. ------------
  40. .. attribute:: django.db.models.signals.pre_init
  41. :module:
  42. .. ^^^^^^^ this :module: hack keeps Sphinx from prepending the module.
  43. Whenever you instantiate a Django model, this signal is sent at the beginning
  44. of the model's ``__init__()`` method.
  45. Arguments sent with this signal:
  46. ``sender``
  47. The model class that just had an instance created.
  48. ``args``
  49. A list of positional arguments passed to ``__init__()``.
  50. ``kwargs``
  51. A dictionary of keyword arguments passed to ``__init__()``.
  52. For example, the :doc:`tutorial </intro/tutorial02>` has this line::
  53. q = Question(question_text="What's new?", pub_date=timezone.now())
  54. The arguments sent to a :data:`pre_init` handler would be:
  55. ========== ===============================================================
  56. Argument Value
  57. ========== ===============================================================
  58. ``sender`` ``Question`` (the class itself)
  59. ``args`` ``[]`` (an empty list because there were no positional
  60. arguments passed to ``__init__()``)
  61. ``kwargs`` ``{'question_text': "What's new?",``
  62. ``'pub_date': datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=datetime.timezone.utc)}``
  63. ========== ===============================================================
  64. ``post_init``
  65. -------------
  66. .. data:: django.db.models.signals.post_init
  67. :module:
  68. Like pre_init, but this one is sent when the ``__init__()`` method finishes.
  69. Arguments sent with this signal:
  70. ``sender``
  71. As above: the model class that just had an instance created.
  72. ``instance``
  73. The actual instance of the model that's just been created.
  74. .. note::
  75. :attr:`instance._state <django.db.models.Model._state>` isn't set
  76. before sending the ``post_init`` signal, so ``_state`` attributes
  77. always have their default values. For example, ``_state.db`` is
  78. ``None``.
  79. .. warning::
  80. For performance reasons, you shouldn't perform queries in receivers of
  81. ``pre_init`` or ``post_init`` signals because they would be executed for
  82. each instance returned during queryset iteration.
  83. ``pre_save``
  84. ------------
  85. .. data:: django.db.models.signals.pre_save
  86. :module:
  87. This is sent at the beginning of a model's :meth:`~django.db.models.Model.save`
  88. method.
  89. Arguments sent with this signal:
  90. ``sender``
  91. The model class.
  92. ``instance``
  93. The actual instance being saved.
  94. ``raw``
  95. A boolean; ``True`` if the model is saved exactly as presented
  96. (i.e. when loading a :ref:`fixture <fixtures-explanation>`). One should not
  97. query/modify other records in the database as the database might not be in
  98. a consistent state yet.
  99. ``using``
  100. The database alias being used.
  101. ``update_fields``
  102. The set of fields to update as passed to :meth:`.Model.save`, or ``None``
  103. if ``update_fields`` wasn't passed to ``save()``.
  104. ``post_save``
  105. -------------
  106. .. data:: django.db.models.signals.post_save
  107. :module:
  108. Like :data:`pre_save`, but sent at the end of the
  109. :meth:`~django.db.models.Model.save` method.
  110. Arguments sent with this signal:
  111. ``sender``
  112. The model class.
  113. ``instance``
  114. The actual instance being saved.
  115. ``created``
  116. A boolean; ``True`` if a new record was created.
  117. ``raw``
  118. A boolean; ``True`` if the model is saved exactly as presented
  119. (i.e. when loading a :ref:`fixture <fixtures-explanation>`). One should not
  120. query/modify other records in the database as the database might not be in
  121. a consistent state yet.
  122. ``using``
  123. The database alias being used.
  124. ``update_fields``
  125. The set of fields to update as passed to :meth:`.Model.save`, or ``None``
  126. if ``update_fields`` wasn't passed to ``save()``.
  127. ``pre_delete``
  128. --------------
  129. .. data:: django.db.models.signals.pre_delete
  130. :module:
  131. Sent at the beginning of a model's :meth:`~django.db.models.Model.delete`
  132. method and a queryset's :meth:`~django.db.models.query.QuerySet.delete` method.
  133. Arguments sent with this signal:
  134. ``sender``
  135. The model class.
  136. ``instance``
  137. The actual instance being deleted.
  138. ``using``
  139. The database alias being used.
  140. ``origin``
  141. The origin of the deletion being the instance of a ``Model`` or
  142. ``QuerySet`` class.
  143. ``post_delete``
  144. ---------------
  145. .. data:: django.db.models.signals.post_delete
  146. :module:
  147. Like :data:`pre_delete`, but sent at the end of a model's
  148. :meth:`~django.db.models.Model.delete` method and a queryset's
  149. :meth:`~django.db.models.query.QuerySet.delete` method.
  150. Arguments sent with this signal:
  151. ``sender``
  152. The model class.
  153. ``instance``
  154. The actual instance being deleted.
  155. Note that the object will no longer be in the database, so be very
  156. careful what you do with this instance.
  157. ``using``
  158. The database alias being used.
  159. ``origin``
  160. The origin of the deletion being the instance of a ``Model`` or
  161. ``QuerySet`` class.
  162. ``m2m_changed``
  163. ---------------
  164. .. data:: django.db.models.signals.m2m_changed
  165. :module:
  166. Sent when a :class:`~django.db.models.ManyToManyField` is changed on a model
  167. instance. Strictly speaking, this is not a model signal since it is sent by the
  168. :class:`~django.db.models.ManyToManyField`, but since it complements the
  169. :data:`pre_save`/:data:`post_save` and :data:`pre_delete`/:data:`post_delete`
  170. when it comes to tracking changes to models, it is included here.
  171. Arguments sent with this signal:
  172. ``sender``
  173. The intermediate model class describing the
  174. :class:`~django.db.models.ManyToManyField`. This class is automatically
  175. created when a many-to-many field is defined; you can access it using the
  176. ``through`` attribute on the many-to-many field.
  177. ``instance``
  178. The instance whose many-to-many relation is updated. This can be an
  179. instance of the ``sender``, or of the class the
  180. :class:`~django.db.models.ManyToManyField` is related to.
  181. ``action``
  182. A string indicating the type of update that is done on the relation.
  183. This can be one of the following:
  184. ``"pre_add"``
  185. Sent *before* one or more objects are added to the relation.
  186. ``"post_add"``
  187. Sent *after* one or more objects are added to the relation.
  188. ``"pre_remove"``
  189. Sent *before* one or more objects are removed from the relation.
  190. ``"post_remove"``
  191. Sent *after* one or more objects are removed from the relation.
  192. ``"pre_clear"``
  193. Sent *before* the relation is cleared.
  194. ``"post_clear"``
  195. Sent *after* the relation is cleared.
  196. ``reverse``
  197. Indicates which side of the relation is updated (i.e., if it is the
  198. forward or reverse relation that is being modified).
  199. ``model``
  200. The class of the objects that are added to, removed from or cleared
  201. from the relation.
  202. ``pk_set``
  203. For the ``pre_add`` and ``post_add`` actions, this is a set of primary key
  204. values that will be, or have been, added to the relation. This may be a
  205. subset of the values submitted to be added, since inserts must filter
  206. existing values in order to avoid a database ``IntegrityError``.
  207. For the ``pre_remove`` and ``post_remove`` actions, this is a set of
  208. primary key values that was submitted to be removed from the relation. This
  209. is not dependent on whether the values actually will be, or have been,
  210. removed. In particular, non-existent values may be submitted, and will
  211. appear in ``pk_set``, even though they have no effect on the database.
  212. For the ``pre_clear`` and ``post_clear`` actions, this is ``None``.
  213. ``using``
  214. The database alias being used.
  215. For example, if a ``Pizza`` can have multiple ``Topping`` objects, modeled
  216. like this::
  217. class Topping(models.Model):
  218. # ...
  219. pass
  220. class Pizza(models.Model):
  221. # ...
  222. toppings = models.ManyToManyField(Topping)
  223. If we connected a handler like this::
  224. from django.db.models.signals import m2m_changed
  225. def toppings_changed(sender, **kwargs):
  226. # Do something
  227. pass
  228. m2m_changed.connect(toppings_changed, sender=Pizza.toppings.through)
  229. and then did something like this:
  230. .. code-block:: pycon
  231. >>> p = Pizza.objects.create(...)
  232. >>> t = Topping.objects.create(...)
  233. >>> p.toppings.add(t)
  234. the arguments sent to a :data:`m2m_changed` handler (``toppings_changed`` in
  235. the example above) would be:
  236. ============== ============================================================
  237. Argument Value
  238. ============== ============================================================
  239. ``sender`` ``Pizza.toppings.through`` (the intermediate m2m class)
  240. ``instance`` ``p`` (the ``Pizza`` instance being modified)
  241. ``action`` ``"pre_add"`` (followed by a separate signal with ``"post_add"``)
  242. ``reverse`` ``False`` (``Pizza`` contains the
  243. :class:`~django.db.models.ManyToManyField`, so this call
  244. modifies the forward relation)
  245. ``model`` ``Topping`` (the class of the objects added to the
  246. ``Pizza``)
  247. ``pk_set`` ``{t.id}`` (since only ``Topping t`` was added to the relation)
  248. ``using`` ``"default"`` (since the default router sends writes here)
  249. ============== ============================================================
  250. And if we would then do something like this:
  251. .. code-block:: pycon
  252. >>> t.pizza_set.remove(p)
  253. the arguments sent to a :data:`m2m_changed` handler would be:
  254. ============== ============================================================
  255. Argument Value
  256. ============== ============================================================
  257. ``sender`` ``Pizza.toppings.through`` (the intermediate m2m class)
  258. ``instance`` ``t`` (the ``Topping`` instance being modified)
  259. ``action`` ``"pre_remove"`` (followed by a separate signal with ``"post_remove"``)
  260. ``reverse`` ``True`` (``Pizza`` contains the
  261. :class:`~django.db.models.ManyToManyField`, so this call
  262. modifies the reverse relation)
  263. ``model`` ``Pizza`` (the class of the objects removed from the
  264. ``Topping``)
  265. ``pk_set`` ``{p.id}`` (since only ``Pizza p`` was removed from the
  266. relation)
  267. ``using`` ``"default"`` (since the default router sends writes here)
  268. ============== ============================================================
  269. ``class_prepared``
  270. ------------------
  271. .. data:: django.db.models.signals.class_prepared
  272. :module:
  273. Sent whenever a model class has been "prepared" -- that is, once a model has
  274. been defined and registered with Django's model system. Django uses this
  275. signal internally; it's not generally used in third-party applications.
  276. Since this signal is sent during the app registry population process, and
  277. :meth:`AppConfig.ready() <django.apps.AppConfig.ready>` runs after the app
  278. registry is fully populated, receivers cannot be connected in that method.
  279. One possibility is to connect them ``AppConfig.__init__()`` instead, taking
  280. care not to import models or trigger calls to the app registry.
  281. Arguments that are sent with this signal:
  282. ``sender``
  283. The model class which was just prepared.
  284. Management signals
  285. ==================
  286. Signals sent by :doc:`django-admin </ref/django-admin>`.
  287. ``pre_migrate``
  288. ---------------
  289. .. data:: django.db.models.signals.pre_migrate
  290. :module:
  291. Sent by the :djadmin:`migrate` command before it starts to install an
  292. application. It's not emitted for applications that lack a ``models`` module.
  293. Arguments sent with this signal:
  294. ``sender``
  295. An :class:`~django.apps.AppConfig` instance for the application about to
  296. be migrated/synced.
  297. ``app_config``
  298. Same as ``sender``.
  299. ``verbosity``
  300. Indicates how much information ``manage.py`` is printing on screen. See
  301. the :option:`--verbosity` flag for details.
  302. Functions which listen for :data:`pre_migrate` should adjust what they
  303. output to the screen based on the value of this argument.
  304. ``interactive``
  305. If ``interactive`` is ``True``, it's safe to prompt the user to input
  306. things on the command line. If ``interactive`` is ``False``, functions
  307. which listen for this signal should not try to prompt for anything.
  308. For example, the :mod:`django.contrib.auth` app only prompts to create a
  309. superuser when ``interactive`` is ``True``.
  310. ``stdout``
  311. A stream-like object where verbose output should be redirected.
  312. ``using``
  313. The alias of database on which a command will operate.
  314. ``plan``
  315. The migration plan that is going to be used for the migration run. While
  316. the plan is not public API, this allows for the rare cases when it is
  317. necessary to know the plan. A plan is a list of 2-tuples with the first
  318. item being the instance of a migration class and the second item showing
  319. if the migration was rolled back (``True``) or applied (``False``).
  320. ``apps``
  321. An instance of :data:`Apps <django.apps>` containing the state of the
  322. project before the migration run. It should be used instead of the global
  323. :attr:`apps <django.apps.apps>` registry to retrieve the models you
  324. want to perform operations on.
  325. ``post_migrate``
  326. ----------------
  327. .. data:: django.db.models.signals.post_migrate
  328. :module:
  329. Sent at the end of the :djadmin:`migrate` (even if no migrations are run) and
  330. :djadmin:`flush` commands. It's not emitted for applications that lack a
  331. ``models`` module.
  332. Handlers of this signal must not perform database schema alterations as doing
  333. so may cause the :djadmin:`flush` command to fail if it runs during the
  334. :djadmin:`migrate` command.
  335. Arguments sent with this signal:
  336. ``sender``
  337. An :class:`~django.apps.AppConfig` instance for the application that was
  338. just installed.
  339. ``app_config``
  340. Same as ``sender``.
  341. ``verbosity``
  342. Indicates how much information ``manage.py`` is printing on screen. See
  343. the :option:`--verbosity` flag for details.
  344. Functions which listen for :data:`post_migrate` should adjust what they
  345. output to the screen based on the value of this argument.
  346. ``interactive``
  347. If ``interactive`` is ``True``, it's safe to prompt the user to input
  348. things on the command line. If ``interactive`` is ``False``, functions
  349. which listen for this signal should not try to prompt for anything.
  350. For example, the :mod:`django.contrib.auth` app only prompts to create a
  351. superuser when ``interactive`` is ``True``.
  352. ``stdout``
  353. A stream-like object where verbose output should be redirected.
  354. ``using``
  355. The database alias used for synchronization. Defaults to the ``default``
  356. database.
  357. ``plan``
  358. The migration plan that was used for the migration run. While the plan is
  359. not public API, this allows for the rare cases when it is necessary to
  360. know the plan. A plan is a list of 2-tuples with the first item being
  361. the instance of a migration class and the second item showing if the
  362. migration was rolled back (``True``) or applied (``False``).
  363. ``apps``
  364. An instance of :data:`Apps <django.apps.apps>` containing the state of the
  365. project after the migration run. It should be used instead of the global
  366. :attr:`apps <django.apps.apps>` registry to retrieve the models you
  367. want to perform operations on.
  368. For example, you could register a callback in an
  369. :class:`~django.apps.AppConfig` like this::
  370. from django.apps import AppConfig
  371. from django.db.models.signals import post_migrate
  372. def my_callback(sender, **kwargs):
  373. # Your specific logic here
  374. pass
  375. class MyAppConfig(AppConfig):
  376. ...
  377. def ready(self):
  378. post_migrate.connect(my_callback, sender=self)
  379. .. note::
  380. If you provide an :class:`~django.apps.AppConfig` instance as the sender
  381. argument, please ensure that the signal is registered in
  382. :meth:`~django.apps.AppConfig.ready`. ``AppConfig``\s are recreated for
  383. tests that run with a modified set of :setting:`INSTALLED_APPS` (such as
  384. when settings are overridden) and such signals should be connected for each
  385. new ``AppConfig`` instance.
  386. Request/response signals
  387. ========================
  388. .. module:: django.core.signals
  389. :synopsis: Core signals sent by the request/response system.
  390. Signals sent by the core framework when processing a request.
  391. .. warning::
  392. Signals can make your code harder to maintain. Consider :doc:`using a
  393. middleware </topics/http/middleware>` before using request/response
  394. signals.
  395. ``request_started``
  396. -------------------
  397. .. data:: django.core.signals.request_started
  398. :module:
  399. Sent when Django begins processing an HTTP request.
  400. Arguments sent with this signal:
  401. ``sender``
  402. The handler class -- e.g. ``django.core.handlers.wsgi.WsgiHandler`` -- that
  403. handled the request.
  404. ``environ``
  405. The ``environ`` dictionary provided to the request.
  406. ``request_finished``
  407. --------------------
  408. .. data:: django.core.signals.request_finished
  409. :module:
  410. Sent when Django finishes delivering an HTTP response to the client.
  411. Arguments sent with this signal:
  412. ``sender``
  413. The handler class, as above.
  414. ``got_request_exception``
  415. -------------------------
  416. .. data:: django.core.signals.got_request_exception
  417. :module:
  418. This signal is sent whenever Django encounters an exception while processing an incoming HTTP request.
  419. Arguments sent with this signal:
  420. ``sender``
  421. Unused (always ``None``).
  422. ``request``
  423. The :class:`~django.http.HttpRequest` object.
  424. Test signals
  425. ============
  426. .. module:: django.test.signals
  427. :synopsis: Signals sent during testing.
  428. Signals only sent when :ref:`running tests <running-tests>`.
  429. ``setting_changed``
  430. -------------------
  431. .. data:: django.test.signals.setting_changed
  432. :module:
  433. This signal is sent when the value of a setting is changed through the
  434. ``django.test.TestCase.settings()`` context manager or the
  435. :func:`django.test.override_settings` decorator/context manager.
  436. It's actually sent twice: when the new value is applied ("setup") and when the
  437. original value is restored ("teardown"). Use the ``enter`` argument to
  438. distinguish between the two.
  439. You can also import this signal from ``django.core.signals`` to avoid importing
  440. from ``django.test`` in non-test situations.
  441. Arguments sent with this signal:
  442. ``sender``
  443. The settings handler.
  444. ``setting``
  445. The name of the setting.
  446. ``value``
  447. The value of the setting after the change. For settings that initially
  448. don't exist, in the "teardown" phase, ``value`` is ``None``.
  449. ``enter``
  450. A boolean; ``True`` if the setting is applied, ``False`` if restored.
  451. ``template_rendered``
  452. ---------------------
  453. .. data:: django.test.signals.template_rendered
  454. :module:
  455. Sent when the test system renders a template. This signal is not emitted during
  456. normal operation of a Django server -- it is only available during testing.
  457. Arguments sent with this signal:
  458. ``sender``
  459. The :class:`~django.template.Template` object which was rendered.
  460. ``template``
  461. Same as sender
  462. ``context``
  463. The :class:`~django.template.Context` with which the template was
  464. rendered.
  465. Database Wrappers
  466. =================
  467. .. module:: django.db.backends
  468. :synopsis: Core signals sent by the database wrapper.
  469. Signals sent by the database wrapper when a database connection is
  470. initiated.
  471. ``connection_created``
  472. ----------------------
  473. .. data:: django.db.backends.signals.connection_created
  474. :module:
  475. Sent when the database wrapper makes the initial connection to the
  476. database. This is particularly useful if you'd like to send any post
  477. connection commands to the SQL backend.
  478. Arguments sent with this signal:
  479. ``sender``
  480. The database wrapper class -- i.e.
  481. ``django.db.backends.postgresql.DatabaseWrapper`` or
  482. ``django.db.backends.mysql.DatabaseWrapper``, etc.
  483. ``connection``
  484. The database connection that was opened. This can be used in a
  485. multiple-database configuration to differentiate connection signals
  486. from different databases.