简体   繁体   中英

Django pre_save instance link not defined

I'm trying to create a simple pre_save function but I get an error kwargs['instance'].link is not defined etc:

why?

I have printed out kwargs['instance'] and I get this:

{'update_fields': None, 'raw': False, 'signal': <django.dispatch.dispatcher.Signal object at 0x10189f750>, 'using': 'default'}

now the strange bit I printed out instance and got the name field test title name

my model:

class Campaign(models.Model):
 name = models.CharField(max_length=60)
    status = models.CharField(max_length=16, choices=MESSAGE_STATUSES, default="Pending",)
    link = models.ForeignKey(Link,  related_name='campaign', null=True)



@receiver(pre_save, sender=Campaign)
    def my_callback(sender, instance, *args, **kwargs):

        print(kwargs)
        print(instance)

        if kwargs['instance'].link is None:
            link = Link()
            link.link = "test"
            link.save()

            kwargs['instance'].link = link
            # No need to save, as we're slipping the value in
            # before we hit the database.

Just use instance.link . kwargs does not contain 'instance' because the function my_callback specify the instance as positional argument.

if instance.link is None:
    ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM