Django Signals are not working properly

I am trying to create a project to create user activity feeds / feeds using blog .

These are models -

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) 

And this is signal.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 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) 

When I create a blog or upload a photo, signal does not work. And I am not mistaken either. But I can manually add elements to the StreamItem application using the administrator, and StreamItem works the way I want. I think there is a problem with signal.py. Please help me. It would be very grateful. Thanks.

+7
django django-signals
source share
2 answers

You must make sure that signals are loaded shortly after starting django. One of the possible ways to ensure its import into the __init__.py module

 # __init__.py # add the below line and run the project again import signals 
+11
source share

If you did not specify the code, the new si element created by your signal handler does not contain the required user field. You probably need to add this to your get_or_create call.

0
source share

All Articles