signals.txt 19 KB

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