Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

python - django post_save call from within sending Model?

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)

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)

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

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

Test shell session:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...