Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 442
jduncan Avatar asked Dec 21 '22 21:12

jduncan


1 Answers

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
like image 128
jpic Avatar answered Jan 03 '23 02:01

jpic