3

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 ?

kamdaou
  • 97
  • 1
  • 8
  • If you override the save method of your customer user you can handle it anywhere including admin. So replace signals with overridden save method or use `pre_save` instead of `post_save` – Ahtisham Feb 01 '22 at 09:22
  • Yes, I overrode it. And even replacing ```post_save``` by ```pre_save``` keep calling the function. By the way, can you explain more why should I use ```pre_save``` instead of ```post_save```, please ? – kamdaou Feb 01 '22 at 14:58

2 Answers2

4

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
Thierno Amadou Sow
  • 2,523
  • 2
  • 5
  • 19
  • 2
    Yep, your answer is helpful. I did not know the existence of this parameter but it solves my problem. Thank you dud. – kamdaou Feb 01 '22 at 15:03
0

post_save signal is sent at the end of the save() method only

spod
  • 21
  • 3
  • That's what I thought also, but mine was not working like that. Finally, what I needed to do was to add ```created``` parameter which help to check if a user has been created before executing my code. Thanks – kamdaou Feb 01 '22 at 15:06