本文介绍了django post_save 从发送模型中调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的模型:

I have a pretty simple model that works:

class Badge(models.Model):

    name = models.CharField(max_length=16, help_text="Name for Badge")
    category = models.ForeignKey(BadgeCategory, help_text="Category for badge")
    description = models.CharField(max_length=32, help_text="A brief description")
    file = models.ImageField(upload_to=format_badge_name)

    signals.post_save.connect(create_badge, sender=Badge)

我知道我在signals.py 中的create_badge 函数有效.如果我在没有发送者值的情况下发送它,它会说发送者是一个 LogEntry 对象.我想/需要在 post_save 脚本中引用一些实例信息,如下所示:

I know my create_badge function in signals.py works. If I send it without a value for sender, it says the sender is a LogEntry object. I want/need to reference some of the instance information in the post_save script like below:

def create_badge(sender, instance, created, **kwargs):

    from userinfuser.ui_api import UserInfuser
    from django.conf import settings

    if created:
        api_key = settings.API_KEY
        api_email = settings.API_EMAIL

        ui = UserInfuser(api_email, api_key)
        ui.create_badge(instance.category.name, instance.name, instance.description, instance.file.url)

我在哪里可以调用我的 post_save 调用,以便它知道徽章(我假设这是修复?

Where can I call my post_save call so it's aware of Badge (I'm assuming this is the fix?

谢谢.

推荐答案

只用sender=Badge连接信号Badge定义,测试示例:

Just connect the signal with sender=Badge after Badge is defined, tested example:

from django.db import models
from django.db.models import signals

def create_badge(sender, instance, created, **kwargs):
    print "Post save emited for", instance

class BadgeCategory(models.Model):
    name = models.CharField(max_length=100)

class Badge(models.Model):

    name = models.CharField(max_length=16, help_text="Name for Badge")
    category = models.ForeignKey(BadgeCategory, help_text="Category for badge")
    description = models.CharField(max_length=32, help_text="A brief description")

signals.post_save.connect(create_badge, sender=Badge)

测试外壳会话:

In [1]: category = BadgeCategory(name='foo')

In [2]: category.save()

In [3]: badge = Badge(category=category, name='bar', description='test badge')

In [4]: badge.save()
Post save emited for Badge object

这篇关于django post_save 从发送模型中调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 21:55