2013-11-28 116 views
7

我正嘗試創建一個項目,以便在blog的幫助下創建用戶的提要/活動源。django信號無法按預期工作

這些模型 -

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) 

當我創建一個博客或上傳照片時,signal不起作用。我也沒有得到任何錯誤。但我可以使用管理員手動將項目添加到StreamItem應用程序,並且StreamItem的確按照我的需要工作。我認爲signals.py有問題。請幫助我。將不勝感激。謝謝。

回答

11

你必須確保信號在django啓動後立即加載。 的一個可能的方式,以確保它是模塊導入__init__.py

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

你好。我在signals.py中添加了__init __。py。但即使現在它不起作用。無論如何檢查錯誤? – Aamu

+0

順便說一句,我必須將'import signals'放入'__init __。py'文件。或者把'__init __。py'放在'signals.py'文件中? – Aamu

+0

@Aamu在應用程序模塊中,您將擁有'__init __。py',它們在加載django時肯定會加載。所以,放入'輸入信號線'在那 – Surya

0

除非您遺漏了代碼,否則信號處理程序創建的新項目si缺少必填字段user。您可能需要將其添加到您的get_or_create調用中。

+0

你好,謝謝你的回答。是的,我沒有添加用戶。但是現在,即使在我添加之後,它也不會創建新的流項目。 – Aamu