小编典典

如何将kwargs从保存传递到post_save信号

python

我连接了一个自定义的post_save信号,发现我似乎找不到一种简单的方法来传递一组kwarg。

在保存过程中(在自定义表单中)

def save(self, commit=True):
    user = super(CustomFormThing, self).save(commit=False)
    #set some other attrs on user here ...
    if commit:
        user.save()

    return user

然后在我的自定义post_save挂钩中,我有以下内容(但从未收到任何花哨的东西)

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    some_id = kwargs.get('some', None)
    other_id = kwargs.get('other', None)

    if created:
        #do something with the kwargs above...

如何将kwargs从保存传递到post_save事件?


阅读 196

收藏
2021-01-20

共1个答案

小编典典

内置信号由Django发送,因此您无法控制它们的扭曲。

您可以:

  1. 定义并发送自己的信号。
  2. 在模型实例中存储其他信息。像这样

    def save(self, commit=True):
    user = super(CustomFormThing, self).save(commit=False)
    #set some other attrs on user here ...
    user._some = 'some'
    user._other = 'other'
    if commit:
        user.save()
    
    return user
    

    @receiver(post_save, sender=User)
    def create_profile(sender, instance, created, **kwargs):
    some_id = getattr(instance, ‘_some’, None)
    other_id = getattr(instance, ‘_other’, None)

    if created:
        #do something with the kwargs above...
    
2021-01-20