signals.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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. 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`` ``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`` ``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. 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. Arguments sent with this signal:
  290. ``sender``
  291. The ``models`` module that was just installed. That is, if
  292. :djadmin:`syncdb` just installed an app called ``"foo.bar.myapp"``,
  293. ``sender`` will be the ``foo.bar.myapp.models`` module.
  294. ``app``
  295. Same as ``sender``.
  296. ``create_models``
  297. A list of the model classes from any app which :djadmin:`syncdb` plans to
  298. create.
  299. ``verbosity``
  300. Indicates how much information manage.py is printing on screen. See
  301. the :djadminopt:`--verbosity` flag for details.
  302. Functions which listen for :data:`pre_syncdb` should adjust what they
  303. output to the screen based on the value of this argument.
  304. ``interactive``
  305. If ``interactive`` is ``True``, it's safe to prompt the user to input
  306. things on the command line. If ``interactive`` is ``False``, functions
  307. which listen for this signal should not try to prompt for anything.
  308. For example, the :mod:`django.contrib.auth` app only prompts to create a
  309. superuser when ``interactive`` is ``True``.
  310. ``db``
  311. The alias of database on which a command will operate.
  312. post_migrate
  313. ------------
  314. .. data:: django.db.models.signals.post_migrate
  315. :module:
  316. Sent by the :djadmin:`migrate` command after it installs an application, and the
  317. :djadmin:`flush` command. It's not emitted for applications that lack a
  318. ``models`` module.
  319. It is important that handlers of this signal perform idempotent changes (e.g.
  320. no database alterations) as this may cause the :djadmin:`flush` management
  321. command to fail if it also ran during the :djadmin:`migrate` command.
  322. Arguments sent with this signal:
  323. ``sender``
  324. An :class:`~django.apps.AppConfig` instance for the application that was
  325. just installed.
  326. ``app_config``
  327. Same as ``sender``.
  328. ``verbosity``
  329. Indicates how much information manage.py is printing on screen. See
  330. the :djadminopt:`--verbosity` flag for details.
  331. Functions which listen for :data:`post_migrate` should adjust what they
  332. output to the screen based on the value of this argument.
  333. ``interactive``
  334. If ``interactive`` is ``True``, it's safe to prompt the user to input
  335. things on the command line. If ``interactive`` is ``False``, functions
  336. which listen for this signal should not try to prompt for anything.
  337. For example, the :mod:`django.contrib.auth` app only prompts to create a
  338. superuser when ``interactive`` is ``True``.
  339. ``using``
  340. The database alias used for synchronization. Defaults to the ``default``
  341. database.
  342. For example, you could register a callback in an
  343. :class:`~django.apps.AppConfig` like this::
  344. from django.apps import AppConfig
  345. from django.db.models.signals import post_migrate
  346. def my_callback(sender, **kwargs):
  347. # Your specific logic here
  348. pass
  349. class MyAppConfig(AppConfig):
  350. ...
  351. def ready(self):
  352. post_migrate.connect(my_callback, sender=self)
  353. post_syncdb
  354. -----------
  355. .. data:: django.db.models.signals.post_syncdb
  356. :module:
  357. .. deprecated:: 1.7
  358. This signal has been replaced by :data:`~django.db.models.signals.post_migrate`.
  359. Sent by the :djadmin:`syncdb` command after it installs an application, and the
  360. :djadmin:`flush` command.
  361. It is important that handlers of this signal perform idempotent changes (e.g.
  362. no database alterations) as this may cause the :djadmin:`flush` management
  363. command to fail if it also ran during the :djadmin:`syncdb` command.
  364. Arguments sent with this signal:
  365. ``sender``
  366. The ``models`` module that was just installed. That is, if
  367. :djadmin:`syncdb` just installed an app called ``"foo.bar.myapp"``,
  368. ``sender`` will be the ``foo.bar.myapp.models`` module.
  369. ``app``
  370. Same as ``sender``.
  371. ``created_models``
  372. A list of the model classes from any app which :djadmin:`syncdb` has
  373. created so far.
  374. ``verbosity``
  375. Indicates how much information manage.py is printing on screen. See
  376. the :djadminopt:`--verbosity` flag for details.
  377. Functions which listen for :data:`post_syncdb` should adjust what they
  378. output to the screen based on the value of this argument.
  379. ``interactive``
  380. If ``interactive`` is ``True``, it's safe to prompt the user to input
  381. things on the command line. If ``interactive`` is ``False``, functions
  382. which listen for this signal should not try to prompt for anything.
  383. For example, the :mod:`django.contrib.auth` app only prompts to create a
  384. superuser when ``interactive`` is ``True``.
  385. ``db``
  386. The database alias used for synchronization. Defaults to the ``default``
  387. database.
  388. For example, ``yourapp/management/__init__.py`` could be written like::
  389. from django.db.models.signals import post_syncdb
  390. import yourapp.models
  391. def my_callback(sender, **kwargs):
  392. # Your specific logic here
  393. pass
  394. post_syncdb.connect(my_callback, sender=yourapp.models)
  395. Request/response signals
  396. ========================
  397. .. module:: django.core.signals
  398. :synopsis: Core signals sent by the request/response system.
  399. Signals sent by the core framework when processing a request.
  400. request_started
  401. ---------------
  402. .. data:: django.core.signals.request_started
  403. :module:
  404. Sent when Django begins processing an HTTP request.
  405. Arguments sent with this signal:
  406. ``sender``
  407. The handler class -- e.g. ``django.core.handlers.wsgi.WsgiHandler`` -- that
  408. handled the request.
  409. ``environ``
  410. The ``environ`` dictionary provided to the request.
  411. .. versionchanged:: 1.8
  412. The ``environ`` argument was added.
  413. request_finished
  414. ----------------
  415. .. data:: django.core.signals.request_finished
  416. :module:
  417. Sent when Django finishes delivering an HTTP response to the client.
  418. .. note::
  419. Some WSGI servers and middleware do not always call ``close`` on the
  420. response object after handling a request, most notably uWSGI prior to 1.2.6
  421. and Sentry's error reporting middleware up to 2.0.7. In those cases this
  422. signal isn't sent at all. This can result in idle connections to database
  423. and memcache servers.
  424. Arguments sent with this signal:
  425. ``sender``
  426. The handler class, as above.
  427. got_request_exception
  428. ---------------------
  429. .. data:: django.core.signals.got_request_exception
  430. :module:
  431. This signal is sent whenever Django encounters an exception while processing an incoming HTTP request.
  432. Arguments sent with this signal:
  433. ``sender``
  434. The handler class, as above.
  435. ``request``
  436. The :class:`~django.http.HttpRequest` object.
  437. Test signals
  438. ============
  439. .. module:: django.test.signals
  440. :synopsis: Signals sent during testing.
  441. Signals only sent when :ref:`running tests <running-tests>`.
  442. setting_changed
  443. ---------------
  444. .. data:: django.test.signals.setting_changed
  445. :module:
  446. This signal is sent when the value of a setting is changed through the
  447. ``django.test.TestCase.settings()`` context manager or the
  448. :func:`django.test.override_settings` decorator/context manager.
  449. It's actually sent twice: when the new value is applied ("setup") and when the
  450. original value is restored ("teardown"). Use the ``enter`` argument to
  451. distinguish between the two.
  452. Arguments sent with this signal:
  453. ``sender``
  454. The settings handler.
  455. ``setting``
  456. The name of the setting.
  457. ``value``
  458. The value of the setting after the change. For settings that initially
  459. don't exist, in the "teardown" phase, ``value`` is ``None``.
  460. ``enter``
  461. .. versionadded:: 1.7
  462. A boolean; ``True`` if the setting is applied, ``False`` if restored.
  463. template_rendered
  464. -----------------
  465. .. data:: django.test.signals.template_rendered
  466. :module:
  467. Sent when the test system renders a template. This signal is not emitted during
  468. normal operation of a Django server -- it is only available during testing.
  469. Arguments sent with this signal:
  470. ``sender``
  471. The :class:`~django.template.Template` object which was rendered.
  472. ``template``
  473. Same as sender
  474. ``context``
  475. The :class:`~django.template.Context` with which the template was
  476. rendered.
  477. Database Wrappers
  478. =================
  479. .. module:: django.db.backends
  480. :synopsis: Core signals sent by the database wrapper.
  481. Signals sent by the database wrapper when a database connection is
  482. initiated.
  483. connection_created
  484. ------------------
  485. .. data:: django.db.backends.signals.connection_created
  486. :module:
  487. Sent when the database wrapper makes the initial connection to the
  488. database. This is particularly useful if you'd like to send any post
  489. connection commands to the SQL backend.
  490. Arguments sent with this signal:
  491. ``sender``
  492. The database wrapper class -- i.e.
  493. ``django.db.backends.postgresql_psycopg2.DatabaseWrapper`` or
  494. ``django.db.backends.mysql.DatabaseWrapper``, etc.
  495. ``connection``
  496. The database connection that was opened. This can be used in a
  497. multiple-database configuration to differentiate connection signals
  498. from different databases.