Is it possible to selectively suppress a post_save (or other) signal in Django?

I am wondering if it is possible to selectively suppress a Django signal (for example, post_saveor post_init) when creating an object or, alternatively, send it certain parameters.

I have an object Userthat can be created in many ways and places in my code. Therefore, to automatically assign a custom object Profileto each User, I use a signal post_save. However, in one specific case, there is additional information that I want to associate with the created object Profile. Passing it as arguments for the signal post_savewould be great, but this is not possible.

Another option is to manually create the object Profile, but then I need to, after saving User, otherwise it Profilecannot be bound to the instance User. However, saving an instance Userleads to the creation of another Profileusing the function called by the signal.

And I can’t just get the newly created object Profile, as this leads to an error 'Profile' object is unsubscriptable. Any tips?

Update:

Here is an example of a possible situation:

def createUserProfile(sender, instance, created, **kwargs):
if created:  
    profile, created = Profile.objects.get_or_create(user=instance)
    if extra_param:
        profile.extra_param = extra_param
    profile.save()

post_save.connect(createUserProfile, sender=User)

def signup(request):
   ...
   extra_param = 'param'
   user.save()

How do I get a variable extra_paramin a method signupfor the createUserProfile method, where it should be saved as part of the object Profile?

+5
source share
2 answers

?

user = User(...)
user.save()
# profile has been created transparently by post_save event
profile = user.profile
profile.extra_stuff = '...'
profile.save()

, , , :

user = User()
user._evil_extra_args = { ... }
user.save()

In event:
extra_args = getattr(user, '_evil_extra_args', False)

, , , , _evil_extra_args .

+2

post_save ( ), . :

class UserProfile(models.Model):  
    user = models.ForeignKey(User)
    other = models.SomeField()

def create_user_profile(sender, instance, created, other_param=None, **kwargs):  
    if created:  
       profile, created = UserProfile.objects.get_or_create(user=instance)
       profile.other(other_param) # or whatever
       profile.save()

post_save.connect(create_user_profile, sender=User, other_param=p)
0

All Articles