[Django]-DjangoCMS: how to auto-add default plugins in placeholders

3👍

This can be done using the CMS_PLACEHOLDER_CONF setting, specifically, the default_plugins option:

CMS_PLACEHOLDER_CONF = {
    'footer': {
        'name': "Footer",
        'default_plugins':[
            {
                'plugin_type':'FooterPlugin',
                'values':{
                    'body':'<p>This is the footer</p>'
                },
            },
        ]
    },
}

This assumes that your FooterPlugin has a field body that allows HTML content.

0👍

One more hint: static placeholders are good for this purposes.

👤Felix

0👍

This is in response to Adam Venturella question above (about plugins with foreign keys) since I just had to solve the same problem … better late than never (maybe)

After digging through the source I found there is a hook you can add to your CMSPlugin after the default plugin is added called notify_on_autoadd. The signature of this is notify_on_autoadd(self, request, conf) where conf is the dict containing the plugin_type, values, etc … so I added the additional foreign keys I wanted as a new key there (it won’t work in the values key since this is passed verbatim as field values to make the CMSPlugin, but you can add it to the root ok) … then in notify_on_autoadd I just make the new entries like normal from this conf.

Here is and example ot make it more clear:

class Story(CMSPlugin):
    title = models.CharField(max_length=32)

    def notify_on_autoadd(self, request, conf):
        new_line_values = conf.get('new_line_values', [])
        for vals in new_line_values:
            line = Line(
                fmt=vals.get('fmt', '')
                text=vals.get('text', ''),
                story=self
            )
            line.save()

    def __str__(self):
        return self.title


class Line(models.Model):
    fmt = models.CharField(max_length=8)
    text = models.TextField()
    story = models.ForeignKey(Story, related_name='story')

    def __str__(self):
        return self.heading

Then you would just add something like this snippet to your CMS_PLACEHOLDER_CONF.

CMS_PLACEHOLDER_CONF = {
    ...
        'default_plugins': [
            {
                'plugin_type':  'StoryPlugin',
                'values': {
                    'title': 'My Story',
                },
                'new_line_values': [
                    {
                        'fmt': 'normal',
                        'text': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
                    },
                    {
                        'fmt': 'bold',
                        'text': 'Everyone is sick of Lorem Ipsum !',
                    },
                ]
            },
        ],
    ...
}

Anyway I hope this helps someone looking for the same thing (I assume Adam Venturella has moved on now)

👤othane

Leave a comment