我有一个非常简单的模型:
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脚本中引用一些实例信息,如下所示:
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调用以便它知道Badge(我假设这是修复?
感谢。
答案 0 :(得分:11)
在定义徽章后,只需将信号与sender = Badge 连接,测试示例:
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)
测试shell会话:
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