andrewjadams3
andrewjadams3

Reputation: 32

String representation of django-cms models/plugins

I've built a custom plugin for a Django CMS project which I've named PageBlockPlugin. The associated PageBlock model features an HTML field, and I've defined a __str__ method on the model which truncates the HTML content to the first three words. When I'm in the Django admin view for this model, I see a list of instances which I've placed in one of my templates:

Page Block Admin View

This looks great! However, when I'm in the frontend editor for the same template and switch to "structure" view, what I see is just a list of instance ids:

Page Block Frontend

I've looked at a number of plugin examples and haven't been able to figure out how to use a model's string representation for it's associated plugin. Any ideas?

Here's a stripped-down version what I've defined so far:

models.py

class PageBlock(CMSPlugin):
    content = HTMLField()

    def __str__(self):
        return Truncator(strip_tags(self.content)).words(3, truncate="...")

cms_plugins.py

class PageBlockPlugin(CMSPluginBase):
    model = models.PageBlock
    name = "Page Block"
    render_template = "some_template.html"

    def render(self, context, instance, placeholder):
        context["instance"] = instance
        return context

plugin_pool.register_plugin(PageBlockPlugin)

admin.py

class PageBlockAdmin(FrontendEditableAdminMixin, admin.ModelAdmin):
    pass

admin.site.register(models.PageBlock, PageBlockAdmin)

Upvotes: 0

Views: 352

Answers (1)

zanderle
zanderle

Reputation: 825

Since you are using Python 2.7, you should use the __unicode__(self) method instead of __str__(self). If you want to use the latter, you can use the @python_2_unicode_compatible decorator. Read more about it here.

Upvotes: 1

Related Questions