Django 1.2: How to connect the pre_save method to a class method

I am trying to define the before_save method in some classes in my django 1.2 project. I am having problems connecting a signal to a class method in models.py.

class MyClass(models.Model): .... def before_save(self, sender, instance, *args, **kwargs): self.test_field = "It worked" 

I tried putting pre_save.connect (before_save, sender = 'self') in 'MyClass', but nothing happens.

I also tried putting it at the end of the models.py file:

 pre_save.connect(MyClass.before_save, sender=MyClass) 

I read about connecting signals to the methods of the here class, but I can not understand the code.

Does anyone know what I'm doing wrong?

+7
source share
3 answers

Instead of using the MyClass method, you should just use the function. Something like:

 def before_save(sender, instance, *args, **kwargs): instance.test_field = "It worked" pre_save.connect(before_save, sender=MyClass) 
-2
source

Working example with classmethod:

 class MyClass(models.Model): #.... @classmethod def before_save(cls, sender, instance, *args, **kwargs): instance.test_field = "It worked" pre_save.connect(MyClass.before_save, sender=MyClass) 

There's also a great decorator for automatic signal processing: http://djangosnippets.org/snippets/2124/

+7
source

I know this question is old, but I was looking for an answer to this earlier today, so why not. It seems from your code you really wanted to use the instance method (from self and field assignment). DataGreed turned to how to use it for a class method, and using signals using instance methods is pretty similar.

 class MyClass(models.Model) test_field = models.Charfield(max_length=100) def __init__(self, *args, **kwargs): super(MyClass, self).__init__(*args, **kwargs) pre_save.connect(self.before_save, sender=MyClass) def before_save(self, sender, instance, *args, **kwargs): self.test_field = "It worked" 

I'm not sure if this is a good idea or not, but it was useful when I needed an instance method called by an object of class A before saving class B.

+3
source

All Articles