Creting feed using signals in Django

天涯浪子 提交于 2019-12-24 16:02:34

问题


Here i have defined a model to create a feed instance in 'models.py':

class StreamItem(models.Model):
  content_type = models.ForeignKey(ContentType)
  object_id = models.PositiveIntegerField()
  pub_date = models.DateTimeField()

  content_object = generic.GenericForeignKey('content_type', 'object_id')

  def get_rendered_html(self):
    template_name = 'streams/stream_item_%s.html' % (self.content_type.name)
    return render_to_string(template_name, { 'object': self.content_object })

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.objects.get_for_model(instance)

            pub_date = instance.pub_date

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

# Send a signal on post_save for each of these models
for modelname in [Fest, College, Event]: 
    my_signal = dispatch.Signal()      
    my_signal.connect(create_stream_item, sender=modelname)

Then i have created views for getting the feed which are working just fine if I create the StreamItem object from the admin site. But, the signals part isn't just working. I am just learning about it, so, I don't understand where I am wrong. Please help.


回答1:


Use post_save signal:

from django.db.models.signals import post_save

for model in [Fest, College, Event]:
    post_save.connect(create_stream_item, sender=model)


来源:https://stackoverflow.com/questions/20770134/creting-feed-using-signals-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!