Search code examples
pythondjangodjango-modelsdjango-cms

How to duplicate inline objects to live?


I am new to Django CMS. I created a plugin with inlines. When I save the plugin and when I publish the page the model gets duplicated but the inline objects are not getting duplicated.

Is there any way to do this? I want my inline objects also to save in live objects when I publish the page.


Solution

  • You need to implement a copy_relations method on your plugin. The documentation is here, but essentially the functionality works like this;

    class ArticlePluginModel(CMSPlugin):
        title = models.CharField(max_length=50)
    
        def copy_relations(self, oldinstance):
            # Before copying related objects from the old instance, the ones
            # on the current one need to be deleted. Otherwise, duplicates may
            # appear on the public version of the page
            self.associated_item.all().delete()
    
            for associated_item in oldinstance.associated_item.all():
                # instance.pk = None; instance.pk.save() is the slightly odd but
                # standard Django way of copying a saved model instance
                associated_item.pk = None
                associated_item.plugin = self
                associated_item.save()
    
    
    class AssociatedItem(models.Model):
        plugin = models.ForeignKey(
            ArticlePluginModel,
            related_name="associated_item"
        )