0

This code is inside a class. I need to access variables defined in the classe's self. How could I pass self to the entry_deletion_images_delete ?

    @receiver(pre_delete, sender=Document, dispatch_uid='document_delete_signal')
    def entry_deletion_images_delete(sender, instance, using, **kwargs):
        for key, value in self.SIZES.items():
            os.remove(self.base_dir + instance.image_main.name)

Since this function uses built in arguments, simply putting self as a new argument is not possible.

Robert Brax
  • 6,508
  • 12
  • 40
  • 69
  • Possible duplicate of [How can I have a Django signal call a model method?](http://stackoverflow.com/questions/12549977/how-can-i-have-a-django-signal-call-a-model-method) – Anentropic Jan 21 '16 at 13:46
  • there's no way this can work as an instance method, you need to use a classmethod http://stackoverflow.com/a/12550857/202168 https://docs.python.org/2/library/functions.html#classmethod – Anentropic Jan 21 '16 at 13:46
  • Sorry, but what is `self`? Which object it is supposed to hold in your case? Isn't it an `instance`? – Alex Morozov Jan 21 '16 at 13:51
  • self is the containing class – Robert Brax Jan 21 '16 at 14:27
  • `self` is the current class instance, so in this case, `instance` param is your `self`. Why isn't it for you? – Gocht Jan 21 '16 at 14:45
  • what was attached to self. in class scope is not accessible from instance inside the function. – Robert Brax Jan 21 '16 at 14:48
  • I'm afraid you might have confused what self is. Anyway, you should put the signals outside the model class. If you want to access a method in the instance you're deleting use the `instance` parameter. – Agustín Lado Jan 21 '16 at 15:15

1 Answers1

0

You are passing to @receiver() an unbound function. You should pass it a bound method, like this:

class MyClass(object):
    def entry_deletion_images_delete(self, sender, instance, using, **kwargs):
        ...

instance = MyClass()
pre_delete.connect(instance.entry_deletion_images_delete, sender=Document, dispatch_uid='document_delete_signal')

In other words, first you have to create an instance (otherwise what would self be?), then you can register the instance method as a receiver for the signal.

What I have shown is just an example. How to actually create the instance and when to connect the receiver depends on your use case.

Andrea Corbellini
  • 17,339
  • 3
  • 53
  • 69