signals.txt 21 KB

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