signals.txt 21 KB

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