signals.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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. .. versionadded:: 1.7
  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. def toppings_changed(sender, **kwargs):
  196. # Do something
  197. pass
  198. m2m_changed.connect(toppings_changed, sender=Pizza.toppings.through)
  199. and then did something like this::
  200. >>> p = Pizza.objects.create(...)
  201. >>> t = Topping.objects.create(...)
  202. >>> p.toppings.add(t)
  203. the arguments sent to a :data:`m2m_changed` handler (``toppings_changed`` in
  204. the example above) would be:
  205. ============== ============================================================
  206. Argument Value
  207. ============== ============================================================
  208. ``sender`` ``Pizza.toppings.through`` (the intermediate m2m class)
  209. ``instance`` ``p`` (the ``Pizza`` instance being modified)
  210. ``action`` ``"pre_add"`` (followed by a separate signal with ``"post_add"``)
  211. ``reverse`` ``False`` (``Pizza`` contains the
  212. :class:`~django.db.models.ManyToManyField`, so this call
  213. modifies the forward relation)
  214. ``model`` ``Topping`` (the class of the objects added to the
  215. ``Pizza``)
  216. ``pk_set`` ``set([t.id])`` (since only ``Topping t`` was added to the relation)
  217. ``using`` ``"default"`` (since the default router sends writes here)
  218. ============== ============================================================
  219. And if we would then do something like this::
  220. >>> t.pizza_set.remove(p)
  221. the arguments sent to a :data:`m2m_changed` handler would be:
  222. ============== ============================================================
  223. Argument Value
  224. ============== ============================================================
  225. ``sender`` ``Pizza.toppings.through`` (the intermediate m2m class)
  226. ``instance`` ``t`` (the ``Topping`` instance being modified)
  227. ``action`` ``"pre_remove"`` (followed by a separate signal with ``"post_remove"``)
  228. ``reverse`` ``True`` (``Pizza`` contains the
  229. :class:`~django.db.models.ManyToManyField`, so this call
  230. modifies the reverse relation)
  231. ``model`` ``Pizza`` (the class of the objects removed from the
  232. ``Topping``)
  233. ``pk_set`` ``set([p.id])`` (since only ``Pizza p`` was removed from the
  234. relation)
  235. ``using`` ``"default"`` (since the default router sends writes here)
  236. ============== ============================================================
  237. class_prepared
  238. --------------
  239. .. data:: django.db.models.signals.class_prepared
  240. :module:
  241. Sent whenever a model class has been "prepared" -- that is, once model has
  242. been defined and registered with Django's model system. Django uses this
  243. signal internally; it's not generally used in third-party applications.
  244. Since this signal is sent during the app registry population process, and
  245. :meth:`AppConfig.ready() <django.apps.AppConfig.ready>` runs after the app
  246. registry is fully populated, receivers cannot be connected in that method.
  247. One possibility is to connect them ``AppConfig.__init__()`` instead, taking
  248. care not to import models or trigger calls to the app registry.
  249. Arguments that are sent with this signal:
  250. ``sender``
  251. The model class which was just prepared.
  252. Management signals
  253. ==================
  254. Signals sent by :doc:`django-admin </ref/django-admin>`.
  255. pre_migrate
  256. -----------
  257. .. data:: django.db.models.signals.pre_migrate
  258. :module:
  259. Sent by the :djadmin:`migrate` command before it starts to install an
  260. application. It's not emitted for applications that lack a ``models`` module.
  261. Arguments sent with this signal:
  262. ``sender``
  263. An :class:`~django.apps.AppConfig` instance for the application about to
  264. be migrated/synced.
  265. ``app_config``
  266. Same as ``sender``.
  267. ``verbosity``
  268. Indicates how much information manage.py is printing on screen. See
  269. the :djadminopt:`--verbosity` flag for details.
  270. Functions which listen for :data:`pre_migrate` should adjust what they
  271. output to the screen based on the value of this argument.
  272. ``interactive``
  273. If ``interactive`` is ``True``, it's safe to prompt the user to input
  274. things on the command line. If ``interactive`` is ``False``, functions
  275. which listen for this signal should not try to prompt for anything.
  276. For example, the :mod:`django.contrib.auth` app only prompts to create a
  277. superuser when ``interactive`` is ``True``.
  278. ``using``
  279. The alias of database on which a command will operate.
  280. pre_syncdb
  281. ----------
  282. .. data:: django.db.models.signals.pre_syncdb
  283. :module:
  284. .. deprecated:: 1.7
  285. This signal has been replaced by :data:`~django.db.models.signals.pre_migrate`.
  286. Sent by the :djadmin:`syncdb` command before it starts to install an
  287. application.
  288. Arguments sent with this signal:
  289. ``sender``
  290. The ``models`` module that was just installed. That is, if
  291. :djadmin:`syncdb` just installed an app called ``"foo.bar.myapp"``,
  292. ``sender`` will be the ``foo.bar.myapp.models`` module.
  293. ``app``
  294. Same as ``sender``.
  295. ``create_models``
  296. A list of the model classes from any app which :djadmin:`syncdb` plans to
  297. create.
  298. ``verbosity``
  299. Indicates how much information manage.py is printing on screen. See
  300. the :djadminopt:`--verbosity` flag for details.
  301. Functions which listen for :data:`pre_syncdb` should adjust what they
  302. output to the screen based on the value of this argument.
  303. ``interactive``
  304. If ``interactive`` is ``True``, it's safe to prompt the user to input
  305. things on the command line. If ``interactive`` is ``False``, functions
  306. which listen for this signal should not try to prompt for anything.
  307. For example, the :mod:`django.contrib.auth` app only prompts to create a
  308. superuser when ``interactive`` is ``True``.
  309. ``using``
  310. The alias of database on which a command will operate.
  311. post_migrate
  312. ------------
  313. .. data:: django.db.models.signals.post_migrate
  314. :module:
  315. Sent by the :djadmin:`migrate` command after it installs an application, and the
  316. :djadmin:`flush` command. It's not emitted for applications that lack a
  317. ``models`` module.
  318. It is important that handlers of this signal perform idempotent changes (e.g.
  319. no database alterations) as this may cause the :djadmin:`flush` management
  320. command to fail if it also ran during the :djadmin:`migrate` command.
  321. Arguments sent with this signal:
  322. ``sender``
  323. An :class:`~django.apps.AppConfig` instance for the application that was
  324. just installed.
  325. ``app_config``
  326. Same as ``sender``.
  327. ``verbosity``
  328. Indicates how much information manage.py is printing on screen. See
  329. the :djadminopt:`--verbosity` flag for details.
  330. Functions which listen for :data:`post_migrate` should adjust what they
  331. output to the screen based on the value of this argument.
  332. ``interactive``
  333. If ``interactive`` is ``True``, it's safe to prompt the user to input
  334. things on the command line. If ``interactive`` is ``False``, functions
  335. which listen for this signal should not try to prompt for anything.
  336. For example, the :mod:`django.contrib.auth` app only prompts to create a
  337. superuser when ``interactive`` is ``True``.
  338. ``db``
  339. The database alias used for synchronization. Defaults to the ``default``
  340. database.
  341. For example, ``yourapp/management/__init__.py`` could be written like::
  342. from django.db.models.signals import post_migrate
  343. import yourapp.models
  344. def my_callback(sender, **kwargs):
  345. # Your specific logic here
  346. pass
  347. post_migrate.connect(my_callback, sender=yourapp.models)
  348. post_syncdb
  349. -----------
  350. .. data:: django.db.models.signals.post_syncdb
  351. :module:
  352. .. deprecated:: 1.7
  353. This signal has been replaced by :data:`~django.db.models.signals.post_migrate`.
  354. Sent by the :djadmin:`syncdb` command after it installs an application, and the
  355. :djadmin:`flush` command.
  356. It is important that handlers of this signal perform idempotent changes (e.g.
  357. no database alterations) as this may cause the :djadmin:`flush` management
  358. command to fail if it also ran during the :djadmin:`syncdb` command.
  359. Arguments sent with this signal:
  360. ``sender``
  361. The ``models`` module that was just installed. That is, if
  362. :djadmin:`syncdb` just installed an app called ``"foo.bar.myapp"``,
  363. ``sender`` will be the ``foo.bar.myapp.models`` module.
  364. ``app``
  365. Same as ``sender``.
  366. ``created_models``
  367. A list of the model classes from any app which :djadmin:`syncdb` has
  368. created so far.
  369. ``verbosity``
  370. Indicates how much information manage.py is printing on screen. See
  371. the :djadminopt:`--verbosity` flag for details.
  372. Functions which listen for :data:`post_syncdb` should adjust what they
  373. output to the screen based on the value of this argument.
  374. ``interactive``
  375. If ``interactive`` is ``True``, it's safe to prompt the user to input
  376. things on the command line. If ``interactive`` is ``False``, functions
  377. which listen for this signal should not try to prompt for anything.
  378. For example, the :mod:`django.contrib.auth` app only prompts to create a
  379. superuser when ``interactive`` is ``True``.
  380. ``db``
  381. The database alias used for synchronization. Defaults to the ``default``
  382. database.
  383. For example, ``yourapp/management/__init__.py`` could be written like::
  384. from django.db.models.signals import post_syncdb
  385. import yourapp.models
  386. def my_callback(sender, **kwargs):
  387. # Your specific logic here
  388. pass
  389. post_syncdb.connect(my_callback, sender=yourapp.models)
  390. Request/response signals
  391. ========================
  392. .. module:: django.core.signals
  393. :synopsis: Core signals sent by the request/response system.
  394. Signals sent by the core framework when processing a request.
  395. request_started
  396. ---------------
  397. .. data:: django.core.signals.request_started
  398. :module:
  399. Sent when Django begins processing an HTTP request.
  400. Arguments sent with this signal:
  401. ``sender``
  402. The handler class -- e.g. ``django.core.handlers.wsgi.WsgiHandler`` -- that
  403. handled the request.
  404. request_finished
  405. ----------------
  406. .. data:: django.core.signals.request_finished
  407. :module:
  408. Sent when Django finishes delivering an HTTP response to the client.
  409. .. note::
  410. Some WSGI servers and middleware do not always call ``close`` on the
  411. response object after handling a request, most notably uWSGI prior to 1.2.6
  412. and Sentry's error reporting middleware up to 2.0.7. In those cases this
  413. signal isn't sent at all. This can result in idle connections to database
  414. and memcache servers.
  415. Arguments sent with this signal:
  416. ``sender``
  417. The handler class, as above.
  418. got_request_exception
  419. ---------------------
  420. .. data:: django.core.signals.got_request_exception
  421. :module:
  422. This signal is sent whenever Django encounters an exception while processing an incoming HTTP request.
  423. Arguments sent with this signal:
  424. ``sender``
  425. The handler class, as above.
  426. ``request``
  427. The :class:`~django.http.HttpRequest` object.
  428. Test signals
  429. ============
  430. .. module:: django.test.signals
  431. :synopsis: Signals sent during testing.
  432. Signals only sent when :ref:`running tests <running-tests>`.
  433. setting_changed
  434. ---------------
  435. .. data:: django.test.signals.setting_changed
  436. :module:
  437. This signal is sent when the value of a setting is changed through the
  438. ``django.test.TestCase.settings()`` context manager or the
  439. :func:`django.test.override_settings` decorator/context manager.
  440. It's actually sent twice: when the new value is applied ("setup") and when the
  441. original value is restored ("teardown"). Use the ``enter`` argument to
  442. distinguish between the two.
  443. Arguments sent with this signal:
  444. ``sender``
  445. The settings handler.
  446. ``setting``
  447. The name of the setting.
  448. ``value``
  449. The value of the setting after the change. For settings that initially
  450. don't exist, in the "teardown" phase, ``value`` is ``None``.
  451. ``enter``
  452. .. versionadded:: 1.7
  453. A boolean; ``True`` if the setting is applied, ``False`` if restored.
  454. template_rendered
  455. -----------------
  456. .. data:: django.test.signals.template_rendered
  457. :module:
  458. Sent when the test system renders a template. This signal is not emitted during
  459. normal operation of a Django server -- it is only available during testing.
  460. Arguments sent with this signal:
  461. ``sender``
  462. The :class:`~django.template.Template` object which was rendered.
  463. ``template``
  464. Same as sender
  465. ``context``
  466. The :class:`~django.template.Context` with which the template was
  467. rendered.
  468. Database Wrappers
  469. =================
  470. .. module:: django.db.backends
  471. :synopsis: Core signals sent by the database wrapper.
  472. Signals sent by the database wrapper when a database connection is
  473. initiated.
  474. connection_created
  475. ------------------
  476. .. data:: django.db.backends.signals.connection_created
  477. :module:
  478. Sent when the database wrapper makes the initial connection to the
  479. database. This is particularly useful if you'd like to send any post
  480. connection commands to the SQL backend.
  481. Arguments sent with this signal:
  482. ``sender``
  483. The database wrapper class -- i.e.
  484. ``django.db.backends.postgresql_psycopg2.DatabaseWrapper`` or
  485. ``django.db.backends.mysql.DatabaseWrapper``, etc.
  486. ``connection``
  487. The database connection that was opened. This can be used in a
  488. multiple-database configuration to differentiate connection signals
  489. from different databases.