djangodjango-authenticationdjango-registration

How can I trigger a function when a user registers in django?


I took over a django web app and am still relatively new to django. I want to trigger a function whenever a new user registers on the website. But there is no code in the project to process the user registration. It all seems to happen under the hood. So I don't know where could put such a function call. The web app uses django.contrib.auth.

Additionally: How can I trigger a function when an account is activated?


Solution

  • You can use the signals to trigger an event when you save anything in your db, include the User from auth. You can see the django doc about this.
    In your case, I think that the best way is like:

    from django.db.models.signals import post_save
    from django.dispatch import receiver
    from django.contrib.auth.models import user
    
    
    @receiver(post_save, sender=User)
    def user_saved(sender, instance, **kwargs):
        ...
    

    In the kwargs you can see, for example, if object is created or modified. The sender is the Class and the instance is the object.