from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.db.models.signals import post_save from django.dispatch import receiver from .syndicators import post_to_medium, build_facebook_feed class Syndicate(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class SyndicatedItem(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') syndicate = models.ManyToManyField(Syndicate) publish_date = models.DateTimeField() STATUS = ( ('1', "Unsent"), ('2', "Sent"), ) status = models.CharField(max_length=1, choices=STATUS, null=True, blank=True) rel_link = models.CharField(max_length=300, null=True, blank=True) def __str__(self): return self.content_object.title def syndicated_to(self): return ','.join(str(synd) for synd in self.syndicate.all()) @receiver(post_save, sender=SyndicatedItem) def post_save_events(sender, update_fields, created, instance, **kwargs): if instance.status == 1: for item in instance.syndicate.all(): if item.name == "Medium": instance.rel_link = post_to_medium(instance.content_object) instance.status = 2 if item.name == "Facebook": build_facebook_feed(instance) instance.status = 2 post_save.disconnect(post_save_events, sender=SyndicatedItem) instance.save() post_save.connect(post_save_events, sender=SyndicatedItem)