问题
Sitting over a day on it. Really can't understand why this signal is not triggered when a user is activated, no error log, no exception in the admin on activation. Can anybody help? The following code should result in a log message in the apache error.log when a user, right?
import logging
from django.dispatch import receiver
from registration.signals import user_activated
@receiver(user_activated)
def registered_callback(sender, **kwargs):
logger = logging.getLogger("user-activated")
logger.error("activated here")
same with user_registered
回答1:
First of all im using django 1.8.3 .You should register your signal first. As far as i know, there are some methods to do that but this is what im doing;
Create signals.py
in your app write your signal there;
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=your_model,dispatch_uid="yourmodel_save_receiver")
def post_save_yourmodel(sender, instance, **kwargs):
if instance.profile_status:
print "active"
else:
print "not active"
Then you should create apps.py
. This file contains configuration information to your model.
from django.apps import AppConfig
class yourmodel_config(AppConfig):
name = 'yourmodel_config'
verbose_name = 'your_model config'
def ready(self):
import yourmodel.signals
With this whenever your app is ready, your signals will be imported
Finally open your __init__.py
and add the following.
default_app_config = 'yourmodel.apps.yourmodel_config'
With this you are defining application configuration for your model.This example when ever yourmodel
is saved, signal checks for profile_status
attribute and prints output depending on the value(true or false) to your console. You can also add created
parameter to your model to know that if instance of the model is created. created
will return True if a new record was created. def post_save_yourmodel(sender, instance, created, **kwargs):
. Otherwise this signal will be triggered whenever your model is saved with yourmodel.save()
.
Consider that is a post_save
example.You can find list of the model signals from here.
来源:https://stackoverflow.com/questions/40392042/why-does-the-signal-not-trigger