信号
A list of all the signals that Django sends. All built-in signals are sentusing the send()
method.
参见
See the documentation on the signal dispatcher forinformation regarding how to register for and receive signals.
The authentication framework sends signals whena user is logged in / out.
Model signals
The django.db.models.signals
module defines a set of signals sent by themodel system.
警告
Many of these signals are sent by various model methods likeinit()
or save()
that you canoverride 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. Toprevent this, pass weak=False
when you call the signal's connect()
.
注解
Model signals sender
model can be lazily referenced when connecting areceiver by specifying its full application label. For example, anQuestion
model defined in the polls
application could be referencedas 'polls.Question'
. This sort of reference can be quite handy whendealing with circular import dependencies and swappable models.
pre_init
django.db.models.signals.
pre_init
- Whenever you instantiate a Django model, this signal is sent at the beginningof 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 tutorial has this line:
- q = Question(question_text="What's new?", pub_date=timezone.now())
The arguments sent to a pre_init
handler would be:
Argument | Value |
---|---|
sender | Question (the class itself) |
args | [] (an empty list because there were no positionalarguments passed to init() ) |
kwargs | {'question_text': "What's new?", 'pub_date': datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)} |
post_init
django.db.models.signals.
post_init
- Like preinit, 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.
注解
instance._state
isn't set before sending the post_init
signal,so _state
attributes always have their default values. For example,_state.db
is None
and cannot be used to check an instance
database.
警告
For performance reasons, you shouldn't perform queries in receivers ofpre_init
or post_init
signals because they would be executed foreach instance returned during queryset iteration.
pre_save
django.db.models.signals.
pre_save
- This is sent at the beginning of a model's
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 otherrecords in the database as the database might not be in aconsistent state yet. using
- The database alias being used.
update_fields
- The set of fields to update as passed to
Model.save()
, orNone
ifupdate_fields
wasn't passed tosave()
.
post_save
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 otherrecords in the database as the database might not be in aconsistent state yet. using
- The database alias being used.
update_fields
- The set of fields to update as passed to
Model.save()
, orNone
ifupdate_fields
wasn't passed tosave()
.
pre_delete
django.db.models.signals.
pre_delete
- Sent at the beginning of a model's
delete()
method and a queryset'sdelete()
method.
Arguments sent with this signal:
sender
- The model class.
instance
- The actual instance being deleted.
using
- The database alias being used.
post_delete
django.db.models.signals.
post_delete
- Like
pre_delete
, but sent at the end of a model'sdelete()
method and a queryset'sdelete()
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 verycareful what you do with this instance.
using
- The database alias being used.
m2m_changed
django.db.models.signals.
m2m_changed
- Sent when a
ManyToManyField
is changed on a modelinstance. Strictly speaking, this is not a model signal since it is sent by theManyToManyField
, but since it complements thepre_save
/post_save
andpre_delete
/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
ManyToManyField
. This class is automaticallycreated when a many-to-many field is defined; you can access it using thethrough
attribute on the many-to-many field. instance
- The instance whose many-to-many relation is updated. This can be aninstance of the
sender
, or of the class theManyToManyField
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 theforward or reverse relation that is being modified).
model
- The class of the objects that are added to, removed from or clearedfrom the relation.
pk_set
- For the
pre_add
,post_add
,pre_remove
andpost_remove
actions, this is a set of primary key values that have been added toor 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 multipleTopping
objects, modeledlike 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 m2m_changed
handler (toppings_changed
inthe 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 theManyToManyField , so this callmodifies the forward relation) |
model | Topping (the class of the objects added to thePizza ) |
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 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 theManyToManyField , so this callmodifies the reverse relation) |
model | Pizza (the class of the objects removed from theTopping ) |
pk_set | {p.id} (since only Pizza p was removed from therelation) |
using | "default" (since the default router sends writes here) |
class_prepared
django.db.models.signals.
class_prepared
- Sent whenever a model class has been "prepared" — that is, once model hasbeen defined and registered with Django's model system. Django uses thissignal internally; it's not generally used in third-party applications.
Since this signal is sent during the app registry population process, andAppConfig.ready()
runs after the appregistry is fully populated, receivers cannot be connected in that method.One possibility is to connect them AppConfig.init()
instead, takingcare 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 django-admin.
pre_migrate
django.db.models.signals.
pre_migrate
- Sent by the
migrate
command before it starts to install anapplication. It's not emitted for applications that lack amodels
module.
Arguments sent with this signal:
sender
- An
AppConfig
instance for the application about tobe migrated/synced. app_config
- Same as
sender
. verbosity
- Indicates how much information manage.py is printing on screen. Seethe
—verbosity
flag for details.
Functions which listen for pre_migrate
should adjust what theyoutput to the screen based on the value of this argument.
interactive
- If
interactive
isTrue
, it's safe to prompt the user to inputthings on the command line. Ifinteractive
isFalse
, functionswhich listen for this signal should not try to prompt for anything.
For example, the django.contrib.auth
app only prompts to create asuperuser when interactive
is True
.
using
- The alias of database on which a command will operate.
plan
- The migration plan that is going to be used for the migration run. Whilethe plan is not public API, this allows for the rare cases when it isnecessary to know the plan. A plan is a list of two-tuples with the firstitem being the instance of a migration class and the second item showingif the migration was rolled back (
True
) or applied (False
). apps
- An instance of
Apps
containing the state of theproject before the migration run. It should be used instead of the globalapps
registry to retrieve the models youwant to perform operations on.
post_migrate
django.db.models.signals.
post_migrate
- Sent at the end of the
migrate
(even if no migrations are run) andflush
commands. It's not emitted for applications that lack amodels
module.
Handlers of this signal must not perform database schema alterations as doingso may cause the flush
command to fail if it runs during themigrate
command.
Arguments sent with this signal:
sender
- An
AppConfig
instance for the application that wasjust installed. app_config
- Same as
sender
. verbosity
- Indicates how much information manage.py is printing on screen. Seethe
—verbosity
flag for details.
Functions which listen for post_migrate
should adjust what theyoutput to the screen based on the value of this argument.
interactive
- If
interactive
isTrue
, it's safe to prompt the user to inputthings on the command line. Ifinteractive
isFalse
, functionswhich listen for this signal should not try to prompt for anything.
For example, the django.contrib.auth
app only prompts to create asuperuser when interactive
is True
.
using
- The database alias used for synchronization. Defaults to the
default
database. plan
- The migration plan that was used for the migration run. While the plan isnot public API, this allows for the rare cases when it is necessary toknow the plan. A plan is a list of two-tuples with the first item beingthe instance of a migration class and the second item showing if themigration was rolled back (
True
) or applied (False
). apps
- An instance of
Apps
containing the state of theproject after the migration run. It should be used instead of the globalapps
registry to retrieve the models youwant to perform operations on.For example, you could register a callback in anAppConfig
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)
注解
If you provide an AppConfig
instance as the senderargument, please ensure that the signal is registered inready()
. AppConfig
s are recreated fortests that run with a modified set of INSTALLED_APPS
(such aswhen settings are overridden) and such signals should be connected for eachnew AppConfig
instance.
Request/response signals
Signals sent by the core framework when processing a request.
request_started
Arguments sent with this signal:
sender
- The handler class — e.g.
django.core.handlers.wsgi.WsgiHandler
— thathandled the request. environ
- The
environ
dictionary provided to the request.
request_finished
django.core.signals.
request_finished
- Sent when Django finishes delivering an HTTP response to the client.
Arguments sent with this signal:
sender
- The handler class, as above.
got_request_exception
django.core.signals.
got_request_exception
- This signal is sent whenever Django encounters an exception while processing an incoming HTTP request.
Arguments sent with this signal:
sender
- Unused (always
None
). request
- The
HttpRequest
object.
Test signals
Signals only sent when running tests.
setting_changed
django.test.signals.
setting_changed
- This signal is sent when the value of a setting is changed through the
django.test.TestCase.settings()
context manager or thedjango.test.override_settings()
decorator/context manager.
It's actually sent twice: when the new value is applied ("setup") and when theoriginal value is restored ("teardown"). Use the enter
argument todistinguish between the two.
You can also import this signal from django.core.signals
to avoid importingfrom 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 initiallydon't exist, in the "teardown" phase,
value
isNone
. enter
- A boolean;
True
if the setting is applied,False
if restored.
template_rendered
django.test.signals.
template_rendered
- Sent when the test system renders a template. This signal is not emitted duringnormal operation of a Django server — it is only available during testing.
Arguments sent with this signal:
sender
- The
Template
object which was rendered. template
- Same as sender
context
- The
Context
with which the template wasrendered.
Database Wrappers
Signals sent by the database wrapper when a database connection isinitiated.
connection_created
django.db.backends.signals.
connection_created
- Sent when the database wrapper makes the initial connection to thedatabase. This is particularly useful if you'd like to send any postconnection commands to the SQL backend.
Arguments sent with this signal:
sender
- The database wrapper class — i.e.
django.db.backends.postgresql.DatabaseWrapper
ordjango.db.backends.mysql.DatabaseWrapper
, etc. connection
- The database connection that was opened. This can be used in amultiple-database configuration to differentiate connection signalsfrom different databases.