开发者

Creating a custom signal for when a user activates his account

I am trying to create a custom signal for when the field auth_user.is_active becomes 1. I looked at Django's docs on signals, but was having trouble understanding how to implement custom signals.

When a user account becomes active, I want to execute the following function:

def new_user(sender, **kwargs)
    profile = User.objects.get(id=user_id).get_profile()
    return RecentActivity(content_object=profile, event_type=1, timestamp=datetime.datetime.now())

How would I do this. And also, what is t开发者_运维知识库he advantage of using signals over just doing the database insert directly? Thank you.


Here is what I did:

# in models.py
@receiver(pre_save, sender=User, dispatch_uid='get_active_user_once')
def new_user_activation_handler(sender, instance, **kwargs):
    if instance.is_active and User.objects.filter(pk=instance.pk, is_active=False).exists():
        profile = User.objects.get(pk=instance.pk).get_profile()
        RecentActivity.objects.create(content_object=profile, event_type=1, timestamp=datetime.datetime.now())


If you want to do something when the field is changing, you can use the approach suggested by Josh, which is essentially to override the __init__ method.

Signals are generally used to communicate between apps. For example auth app sends user_logged_in signal. So if you want to do something when user is logging in, you just handle this signal, no need to patch the app.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜