signals.txt 18 KB

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