python - 如何将 kwargs 从 save 传递到 post_save 信号

标签 python django

我正在连接一个自定义 post_save 信号,并注意到我似乎无法找到一种简单的方法来传递一组 kwargs。

在保存期间(在自定义表单中)

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 钩子(Hook)中,我有以下内容(但从未得到任何 kwargs)

@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 从 save 传递到 post_save 事件?

最佳答案

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

你可以:

  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...
    

关于python - 如何将 kwargs 从 save 传递到 post_save 信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10299034/

相关文章:

python - PyPy:不能对 ast 类进行 Monkeypatch 吗?

Python GTK +3 : Sorting a treeview by clicking on column

python - 截断一个数字并获取删除的值。还是转换为 int?

python - 根据django的选择从数据库中获取数据

django - 如何在django python中压缩上传的图像

python - upwork-api client.auth.get_request_token() 返回 (null,null)

python - django queryset.update(**kwargs) 上的原子事务

python - Django:通过导致 'current transaction is aborted, commands ignored until end of transaction block' 添加 m2m

python - Django : An established connection was aborted by the software in your host machine

python - 如何在django中删除项目