【问题标题】:django signals module object has no attribute connectdjango 信号模块对象没有属性连接
【发布时间】:2013-12-15 16:12:06
【问题描述】:

我正在尝试创建一个项目,用于在博客的帮助下创建用户的提要/活动提要。

这是信号.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(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)

当我尝试运行服务器时,它给了我一个错误:

AttributeError: 'module' 对象没有属性 'connect'

请帮帮我。将不胜感激。谢谢。

【问题讨论】:

    标签: django python-2.7 django-signals django-1.5


    【解决方案1】:

    替换

    from django.dispatch import dispatcher -> from django.dispatch import Signal

    dispatcher.connect -> Signal.connect

    dispatcher 是模块,interpreter 告诉你。

    【讨论】:

    • 感谢您的回答。但经过上述更改后,又出现了一个错误:unbound method connect() must be called with Signals instance as a first argument (got function instance instead)
    • 试试signals.post_save.connect(create_stream_item, sender=modelname)。您的变体看起来像旧的 django 信号连接。
    • 好的,做到了!非常感谢。
    • Django 有非常好的和紧急的文档 - docs.djangoproject.com/en/dev/topics/signals.
    • 好的,知道了!谢谢! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    相关资源
    最近更新 更多