pythondjangosignalsdjango-custom-user

signal for custom user registration in django


help please !!

I have a custom user model that I am using in my project. And I create a wallet to my new users by using signal, when they register.

@receiver(post_save, sender=User)
def create_saving_wallet(sender, instance, **kwargs):
    [...]

In the function, I am doing basic things like

wallet = Wallet(user_id=user_id, wallet_type=wallet_type, amout=amount)
wallet.save()

And, I have in app.py this class to send the signal :

from django.apps import AppConfig
from django.core.signals import request_finished


class MyAppConfig(AppConfig):

    def ready(self):
        from wallet import views
        # Explicitly connect a signal handler.
        request_finished.connect(views.create_saving_wallet, dispatch_uid="azerty123")

Everything work well when we use the registration form, but if we use admin site to login the signal is called and then the old wallet is updated.

How can I do to avoid this behavior ?

The signal should just be called when save() method of my custom user is called. I am not sure but since I have this bug, does it mean that when a user logged in, save() method is called ?


Solution

  • try this note that in post_save there is a parameter created that will be useful created has two values(True and False).True is when the User is first created.

    @receiver(post_save, sender=User)
    def create_saving_wallet(sender,instance,created,*args,**kwargs):
        if created:
           # add your code here