Search code examples
pythondjangodjango-admindjango-cms

manytomany field not working django-cms


I am using django-cms many to many field is working fine when i add plugins or update but after publish page i didn't get any data where i add many to many field.

models are look like this

@python_2_unicode_compatible
class ClientLogo(CMSPlugin):
  client_logo = models.ManyToManyField(LogoPluginModel, blank=True)

class LogoPluginModel(CMSPlugin):
  title = models.CharField(max_length=100)

here field 'client_logo' will be disapper when i publish djagno-cms page


Solution

  • The relations need to be explicitly copied through the copy_relations method (see django-cms models manual). It's also advantageous to add a related_name property to the ManyToManyField, especially when a model contains multiple sets of foreign keys or ManyToManyFields.

    @python_2_unicode_compatible
    class ClientLogo(CMSPlugin):
      client_logo = models.ManyToManyField(
        LogoPluginModel,
        blank=True,
        related_name='client_logos',
      )
    
    
    class LogoPluginModel(CMSPlugin):
      title = models.CharField(max_length=100)
    
      def copy_relations(self, oldinstance):
        self.client_logos.all().delete()
        for logo in oldinstance.client_logos.all():
          logo.pk = None
          logo.showroom = self
          logo.save()