Arthur de Jong

Open Source / Free Software developer

summaryrefslogtreecommitdiffstats
path: root/docs/ref/signals.txt
blob: ca6f9c2de690157eb3719e3cc9318f2932655fa2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
=======
Signals
=======

A list of all the signals that Django sends.

.. seealso::

    See the documentation on the :doc:`signal dispatcher </topics/signals>` for
    information regarding how to register for and receive signals.

    The :doc:`authentication framework </topics/auth/index>` sends :ref:`signals when
    a user is logged in / out <topics-auth-signals>`.

Model signals
=============

.. module:: django.db.models.signals
   :synopsis: Signals sent by the model system.

The :mod:`django.db.models.signals` module defines a set of signals sent by the
model system.

.. warning::

    Many of these signals are sent by various model methods like
    ``__init__()`` or :meth:`~django.db.models.Model.save` that you can
    override in your own code.

    If you override these methods on your model, you must call the parent class'
    methods for this signals to be sent.

    Note also that Django stores signal handlers as weak references by default,
    so if your handler is a local function, it may be garbage collected.  To
    prevent this, pass ``weak=False`` when you call the signal's :meth:`~django.dispatch.Signal.connect`.

.. note::

    Model signals ``sender`` model can be lazily referenced when connecting a
    receiver by specifying its full application label. For example, an
    ``Answer`` model defined in the ``polls`` application could be referenced
    as ``'polls.Answer'``. This sort of reference can be quite handy when
    dealing with circular import dependencies and swappable models.

pre_init
--------

.. attribute:: django.db.models.signals.pre_init
   :module:

.. ^^^^^^^ this :module: hack keeps Sphinx from prepending the module.

Whenever you instantiate a Django model, this signal is sent at the beginning
of the model's ``__init__()`` method.

Arguments sent with this signal:

``sender``
    The model class that just had an instance created.

``args``
    A list of positional arguments passed to ``__init__()``:

``kwargs``
    A dictionary of keyword arguments passed to ``__init__()``:

For example, the :doc:`tutorial </intro/tutorial01>` has this line::

    p = Poll(question="What's up?", pub_date=datetime.now())

The arguments sent to a :data:`pre_init` handler would be:

==========  ===============================================================
Argument    Value
==========  ===============================================================
``sender``  ``Poll`` (the class itself)

``args``    ``[]`` (an empty list because there were no positional
            arguments passed to ``__init__()``.)

``kwargs``  ``{'question': "What's up?", 'pub_date': datetime.now()}``
==========  ===============================================================

post_init
---------

.. data:: django.db.models.signals.post_init
   :module:

Like pre_init, but this one is sent when the ``__init__()`` method finishes.

Arguments sent with this signal:

``sender``
    As above: the model class that just had an instance created.

``instance``
    The actual instance of the model that's just been created.

pre_save
--------

.. data:: django.db.models.signals.pre_save
   :module:

This is sent at the beginning of a model's :meth:`~django.db.models.Model.save`
method.

Arguments sent with this signal:

``sender``
    The model class.

``instance``
    The actual instance being saved.

``raw``
    A boolean; ``True`` if the model is saved exactly as presented
    (i.e. when loading a fixture). One should not query/modify other
    records in the database as the database might not be in a
    consistent state yet.

``using``
    The database alias being used.

``update_fields``
    The set of fields to update explicitly specified in the ``save()`` method.
    ``None`` if this argument was not used in the ``save()`` call.

post_save
---------

.. data:: django.db.models.signals.post_save
   :module:

Like :data:`pre_save`, but sent at the end of the
:meth:`~django.db.models.Model.save` method.

Arguments sent with this signal:

``sender``
    The model class.

``instance``
    The actual instance being saved.

``created``
    A boolean; ``True`` if a new record was created.

``raw``
    A boolean; ``True`` if the model is saved exactly as presented
    (i.e. when loading a fixture). One should not query/modify other
    records in the database as the database might not be in a
    consistent state yet.

``using``
    The database alias being used.

``update_fields``
    The set of fields to update explicitly specified in the ``save()`` method.
    ``None`` if this argument was not used in the ``save()`` call.

pre_delete
----------

.. data:: django.db.models.signals.pre_delete
   :module:

Sent at the beginning of a model's :meth:`~django.db.models.Model.delete`
method and a queryset's :meth:`~django.db.models.query.QuerySet.delete` method.

Arguments sent with this signal:

``sender``
    The model class.

``instance``
    The actual instance being deleted.

``using``
    The database alias being used.

post_delete
-----------

.. data:: django.db.models.signals.post_delete
   :module:

Like :data:`pre_delete`, but sent at the end of a model's
:meth:`~django.db.models.Model.delete` method and a queryset's
:meth:`~django.db.models.query.QuerySet.delete` method.

Arguments sent with this signal:

``sender``
    The model class.

``instance``
    The actual instance being deleted.

    Note that the object will no longer be in the database, so be very
    careful what you do with this instance.

``using``
    The database alias being used.

m2m_changed
-----------

.. data:: django.db.models.signals.m2m_changed
   :module:

Sent when a :class:`~django.db.models.ManyToManyField` is changed on a model
instance. Strictly speaking, this is not a model signal since it is sent by the
:class:`~django.db.models.ManyToManyField`, but since it complements the
:data:`pre_save`/:data:`post_save` and :data:`pre_delete`/:data:`post_delete`
when it comes to tracking changes to models, it is included here.

Arguments sent with this signal:

``sender``
    The intermediate model class describing the
    :class:`~django.db.models.ManyToManyField`. This class is automatically
    created when a many-to-many field is defined; you can access it using the
    ``through`` attribute on the many-to-many field.

``instance``
    The instance whose many-to-many relation is updated. This can be an
    instance of the ``sender``, or of the class the
    :class:`~django.db.models.ManyToManyField` is related to.

``action``
    A string indicating the type of update that is done on the relation.
    This can be one of the following:

    ``"pre_add"``
        Sent *before* one or more objects are added to the relation.
    ``"post_add"``
        Sent *after* one or more objects are added to the relation.
    ``"pre_remove"``
        Sent *before* one or more objects are removed from the relation.
    ``"post_remove"``
        Sent *after* one or more objects are removed from the relation.
    ``"pre_clear"``
        Sent *before* the relation is cleared.
    ``"post_clear"``
        Sent *after* the relation is cleared.

``reverse``
    Indicates which side of the relation is updated (i.e., if it is the
    forward or reverse relation that is being modified).

``model``
    The class of the objects that are added to, removed from or cleared
    from the relation.

``pk_set``
    For the ``pre_add``, ``post_add``, ``pre_remove`` and ``post_remove``
    actions, this is a set of primary key values that have been added to
    or removed from the relation.

    For the ``pre_clear`` and ``post_clear`` actions, this is ``None``.

``using``
    The database alias being used.

For example, if a ``Pizza`` can have multiple ``Topping`` objects, modeled
like this::

    class Topping(models.Model):
        # ...
        pass

    class Pizza(models.Model):
        # ...
        toppings = models.ManyToManyField(Topping)

If we connected a handler like this::

    from django.db.models.signals import m2m_changed

    def toppings_changed(sender, **kwargs):
        # Do something
        pass

    m2m_changed.connect(toppings_changed, sender=Pizza.toppings.through)

and then did something like this::

    >>> p = Pizza.objects.create(...)
    >>> t = Topping.objects.create(...)
    >>> p.toppings.add(t)

the arguments sent to a :data:`m2m_changed` handler (``toppings_changed`` in
the example above) would be:

==============  ============================================================
Argument        Value
==============  ============================================================
``sender``      ``Pizza.toppings.through`` (the intermediate m2m class)

``instance``    ``p`` (the ``Pizza`` instance being modified)

``action``      ``"pre_add"`` (followed by a separate signal with ``"post_add"``)

``reverse``     ``False`` (``Pizza`` contains the
                :class:`~django.db.models.ManyToManyField`, so this call
                modifies the forward relation)

``model``       ``Topping`` (the class of the objects added to the
                ``Pizza``)

``pk_set``      ``{t.id}`` (since only ``Topping t`` was added to the relation)

``using``       ``"default"`` (since the default router sends writes here)
==============  ============================================================

And if we would then do something like this::

    >>> t.pizza_set.remove(p)

the arguments sent to a :data:`m2m_changed` handler would be:

==============  ============================================================
Argument        Value
==============  ============================================================
``sender``      ``Pizza.toppings.through`` (the intermediate m2m class)

``instance``    ``t`` (the ``Topping`` instance being modified)

``action``      ``"pre_remove"`` (followed by a separate signal with ``"post_remove"``)

``reverse``     ``True`` (``Pizza`` contains the
                :class:`~django.db.models.ManyToManyField`, so this call
                modifies the reverse relation)

``model``       ``Pizza`` (the class of the objects removed from the
                ``Topping``)

``pk_set``      ``{p.id}`` (since only ``Pizza p`` was removed from the
                relation)

``using``       ``"default"`` (since the default router sends writes here)
==============  ============================================================

class_prepared
--------------

.. data:: django.db.models.signals.class_prepared
   :module:

Sent whenever a model class has been "prepared" -- that is, once model has
been defined and registered with Django's model system. Django uses this
signal internally; it's not generally used in third-party applications.

Since this signal is sent during the app registry population process, and
:meth:`AppConfig.ready() <django.apps.AppConfig.ready>` runs after the app
registry is fully populated, receivers cannot be connected in that method.
One possibility is to connect them ``AppConfig.__init__()`` instead, taking
care not to import models or trigger calls to the app registry.

Arguments that are sent with this signal:

``sender``
    The model class which was just prepared.

Management signals
==================

Signals sent by :doc:`django-admin </ref/django-admin>`.

pre_migrate
-----------

.. data:: django.db.models.signals.pre_migrate
   :module:

Sent by the :djadmin:`migrate` command before it starts to install an
application. It's not emitted for applications that lack a ``models`` module.

Arguments sent with this signal:

``sender``
    An :class:`~django.apps.AppConfig` instance for the application about to
    be migrated/synced.

``app_config``
    Same as ``sender``.

``verbosity``
    Indicates how much information manage.py is printing on screen. See
    the :djadminopt:`--verbosity` flag for details.

    Functions which listen for :data:`pre_migrate` should adjust what they
    output to the screen based on the value of this argument.

``interactive``
    If ``interactive`` is ``True``, it's safe to prompt the user to input
    things on the command line. If ``interactive`` is ``False``, functions
    which listen for this signal should not try to prompt for anything.

    For example, the :mod:`django.contrib.auth` app only prompts to create a
    superuser when ``interactive`` is ``True``.

``using``
    The alias of database on which a command will operate.

post_migrate
------------

.. data:: django.db.models.signals.post_migrate
   :module:

Sent by the :djadmin:`migrate` command after it installs an application, and the
:djadmin:`flush` command. It's not emitted for applications that lack a
``models`` module.

It is important that handlers of this signal perform idempotent changes (e.g.
no database alterations) as this may cause the :djadmin:`flush` management
command to fail if it also ran during the :djadmin:`migrate` command.

Arguments sent with this signal:

``sender``
    An :class:`~django.apps.AppConfig` instance for the application that was
    just installed.

``app_config``
    Same as ``sender``.

``verbosity``
    Indicates how much information manage.py is printing on screen. See
    the :djadminopt:`--verbosity` flag for details.

    Functions which listen for :data:`post_migrate` should adjust what they
    output to the screen based on the value of this argument.

``interactive``
    If ``interactive`` is ``True``, it's safe to prompt the user to input
    things on the command line. If ``interactive`` is ``False``, functions
    which listen for this signal should not try to prompt for anything.

    For example, the :mod:`django.contrib.auth` app only prompts to create a
    superuser when ``interactive`` is ``True``.

``using``
    The database alias used for synchronization. Defaults to the ``default``
    database.

For example, you could register a callback in an
:class:`~django.apps.AppConfig` like this::

    from django.apps import AppConfig
    from django.db.models.signals import post_migrate

    def my_callback(sender, **kwargs):
        # Your specific logic here
        pass

    class MyAppConfig(AppConfig):
        ...

        def ready(self):
            post_migrate.connect(my_callback, sender=self)

.. note::

    If you provide an :class:`~django.apps.AppConfig` instance as the sender
    argument, please ensure that the signal is registered in
    :meth:`~django.apps.AppConfig.ready`. ``AppConfig``\s are recreated for
    tests that run with a modified set of :setting:`INSTALLED_APPS` (such as
    when settings are overridden) and such signals should be connected for each
    new ``AppConfig`` instance.

Request/response signals
========================

.. module:: django.core.signals
   :synopsis: Core signals sent by the request/response system.

Signals sent by the core framework when processing a request.

request_started
---------------

.. data:: django.core.signals.request_started
   :module:

Sent when Django begins processing an HTTP request.

Arguments sent with this signal:

``sender``
    The handler class -- e.g. ``django.core.handlers.wsgi.WsgiHandler`` -- that
    handled the request.
``environ``
    The ``environ`` dictionary provided to the request.

request_finished
----------------

.. data:: django.core.signals.request_finished
   :module:

Sent when Django finishes delivering an HTTP response to the client.

.. note::

    Some WSGI servers and middleware do not always call ``close`` on the
    response object after handling a request, most notably uWSGI prior to 1.2.6
    and Sentry's error reporting middleware up to 2.0.7. In those cases this
    signal isn't sent at all. This can result in idle connections to database
    and memcache servers.

Arguments sent with this signal:

``sender``
    The handler class, as above.

got_request_exception
---------------------

.. data:: django.core.signals.got_request_exception
   :module:

This signal is sent whenever Django encounters an exception while processing an incoming HTTP request.

Arguments sent with this signal:

``sender``
    The handler class, as above.

``request``
    The :class:`~django.http.HttpRequest` object.

Test signals
============

.. module:: django.test.signals
   :synopsis: Signals sent during testing.

Signals only sent when :ref:`running tests <running-tests>`.

setting_changed
---------------

.. data:: django.test.signals.setting_changed
   :module:

This signal is sent when the value of a setting is changed through the
``django.test.TestCase.settings()`` context manager or the
:func:`django.test.override_settings` decorator/context manager.

It's actually sent twice: when the new value is applied ("setup") and when the
original value is restored ("teardown"). Use the ``enter`` argument to
distinguish between the two.

You can also import this signal from ``django.core.signals`` to avoid importing
from ``django.test`` in non-test situations.

Arguments sent with this signal:

``sender``
    The settings handler.

``setting``
    The name of the setting.

``value``
    The value of the setting after the change. For settings that initially
    don't exist, in the "teardown" phase, ``value`` is ``None``.

``enter``
    A boolean; ``True`` if the setting is applied, ``False`` if restored.

template_rendered
-----------------

.. data:: django.test.signals.template_rendered
   :module:

Sent when the test system renders a template. This signal is not emitted during
normal operation of a Django server -- it is only available during testing.

Arguments sent with this signal:

``sender``
    The :class:`~django.template.Template` object which was rendered.

``template``
    Same as sender

``context``
    The :class:`~django.template.Context` with which the template was
    rendered.

Database Wrappers
=================

.. module:: django.db.backends
   :synopsis: Core signals sent by the database wrapper.

Signals sent by the database wrapper when a database connection is
initiated.

connection_created
------------------

.. data:: django.db.backends.signals.connection_created
   :module:

Sent when the database wrapper makes the initial connection to the
database.  This is particularly useful if you'd like to send any post
connection commands to the SQL backend.

Arguments sent with this signal:

``sender``
    The database wrapper class -- i.e.
    ``django.db.backends.postgresql.DatabaseWrapper`` or
    ``django.db.backends.mysql.DatabaseWrapper``, etc.

``connection``
    The database connection that was opened. This can be used in a
    multiple-database configuration to differentiate connection signals
    from different databases.