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

拈花ヽ惹草 提交于 2019-12-03 07:46:08

Why this doesn't work for you?

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

If you are obsessed with parameters passing to event, possible but evil:

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

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

It is evil because people who will read your code will have no idea what the heck those _evil_extra_args is for and how does it work.

Yuval Adam

Delaying post_save is not possible (unless you want to entirely disconnect it), but neither is it necessary. Passing a parameter to the profile is not a problem at all:

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!