2

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 the advantage of using signals over just doing the database insert directly? Thank you.

David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

2

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())
David542
  • 104,438
  • 178
  • 489
  • 842
  • Have you clicked the link I provided? You can do it without extra DB query. – DrTyrsa Jun 30 '11 at 21:11
  • 1
    @DrTyrsa -- the auth app link? I wasn't quite sure how to do it without an extra db query. Could you please elaborate with what you mean (a code sample would be great). Thank you. – David542 Jun 30 '11 at 21:16
  • @David542: Thanks, this is exactly what I was looking for. IMO, this should be accepted answer. The currently accepted answer is just general advice referencing external links. – Hooman Bahreini Aug 12 '22 at 03:23
0

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.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
DrTyrsa
  • 31,014
  • 7
  • 86
  • 86
  • 1
    what if I only want to send a signal on the first user log in? – David542 Jun 30 '11 at 09:08
  • 1
    @David542 You should store a flag like `signal_sent` somewhere. BTW is it possible in your application that user will become inactive again? If not - here's the flag. – DrTyrsa Jun 30 '11 at 09:10