Django 1.2:如何将pre_save信号连接到class方法 [英] Django 1.2: How to connect pre_save signal to class method

查看:124
本文介绍了Django 1.2:如何将pre_save信号连接到class方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的django 1.2项目中的某些类中定义一个before_save方法。我无法将信号连接到models.py中的类方法。

  class MyClass(models.Model):
....
def before_save(self,sender,instance,* args,** kwargs):
self.test_field =它工作

我已经尝试在'MyClass'本身放置pre_save.connect(before_save,sender ='self'),但没有任何反应。



我也尝试将它放在models.py文件的底部:

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

我阅读了关于将信号连接到类方法此处,但无法弄清楚



任何人知道我在做错什么?

解决方案

而不是在MyClass上使用一个方法,你应该只使用一个函数。如下所示:

  def before_save(sender,instance,* args,** kwargs):
instance.test_field = 工作

pre_save.connect(before_save,sender = MyClass)


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.

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

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

I've also tried putting it at the bottom of the models.py file:

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

I read about connecting signals to class methods here, but can't figure out the code.

Anybody know what I'm doing wrong?

解决方案

Rather than use a method on MyClass, you should just use a function. Something like:

def before_save(sender, instance, *args, **kwargs):
    instance.test_field = "It worked"

pre_save.connect(before_save, sender=MyClass)

这篇关于Django 1.2:如何将pre_save信号连接到class方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆