django信号未按预期工作

django信号未按预期工作,django,django-signals,Django,Django Signals,我正在尝试创建一个项目,以便在用户的帮助下创建用户的提要/活动提要 这些是模型- class StreamItem(models.Model): user = models.ForeignKey(User) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() pub_date = models.DateTimeField(default=da

我正在尝试创建一个项目,以便在用户的帮助下创建用户的提要/活动提要

这些是模型-

class StreamItem(models.Model):
    user = models.ForeignKey(User)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    pub_date = models.DateTimeField(default=datetime.now)
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    @property 
    def content_class(self):
        return self.content_type.model


class Blog(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=300)
    body = models.TextField()
    pub_date = models.DateTimeField(default=datetime.now)


class Photo(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=200)
    image = models.ImageField(upload_to=get_upload_file_name)
    pub_date = models.DateTimeField(default=datetime.now)
这是signals.py:

__init__.py
from django.db.models import signals
from django.contrib.contenttypes.models import ContentType
from django.dispatch import dispatcher
from blogs.models import Blog
from picture.models import Photo
from models import StreamItem

def create_stream_item(sender, instance, signal, *args, **kwargs):

    # Check to see if the object was just created for the first time

    if 'created' in kwargs:
        if kwargs['created']:
            create = True

            # Get the instance's content type

            ctype = ContentType.object.get_for_model(instance)

            if create:
                si = StreamItem.objects.get_or_create(user=instance.user, content_type=ctype, object_id=instance.id, pub_date = instance.pub_date)

 # Send a signal on post_save for each of these models

for modelname in [Blog, Photo]:
    dispatcher.connect(create_stream_item, signal=signals.post_save, sender=modelname)

当我创建博客或上传照片时,
信号不起作用。我也没有得到任何错误。但是我可以使用管理员手动将项目添加到
StreamItem
应用程序中,并且StreamItem确实可以按我所希望的方式工作。我觉得信号有问题。请帮帮我。非常感谢。谢谢。

除非您省略了代码,否则您的信号处理程序创建的新
si
项缺少所需字段
user
。您可能需要将其添加到您的
get\u或\u create
调用中。

您必须确保在django启动后立即加载信号。 确保它的一种可能的方法是将模块导入
\uuuu init\uuuuuuuuu.py

# __init__.py
# add the below line and run the project again
import signals

嗨,谢谢你的回答。是的,我没有添加用户。但是现在,即使在我添加之后,它也不会创建新的流项目。我已经在signals.py中添加了
\uuuu init\uuuuuuuuuuuuuuuuuuuuuuuuuupy
。但即使现在它也不起作用。是否仍有检查错误的方法?顺便问一下,我是否必须将
导入信号
放入
\uuuu init\uuuuuuuuuy.py
文件中。或者将
\uuuu init\uuuuuuuuuuuupy
放在
signals.py
文件中?@Aamu中的应用程序模块中,您将拥有
\uuuuu init\uuuuuuuuuuuuuuuuuupy
,在加载django时肯定会加载这些模块。所以,把导入信号的
行放到那行,好吧,现在我想这行了。。。但是我得到了另一个错误:
AttributeError:“module”对象没有属性“connect”
Ok,我不得不更改一些代码,它成功了。但是init.py文件中的导入信号解决了信号的触发问题。非常感谢。