signals.txt 18 KB

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