Django 1.2: How to connect pre_save signal to class method

前端 未结 3 572
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 11:34

I am trying to define a \"before_save\" method in certain classes in my django 1.2 project. I\'m having trouble connecting the signal to the class method in models.py.

3条回答
  •  借酒劲吻你
    2021-01-12 12:23

    A 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 to handle signal connections automatically: http://djangosnippets.org/snippets/2124/

提交回复
热议问题