我在Django / Django-CMS中为我的项目创建了一个自定义插件,该插件有一个用户在将插件添加到页面时选择的推荐列表。模型是这样的:
class TestimonialsPlugin(CMSPlugin):
n_testimonials = models.PositiveIntegerField(
verbose_name=_('Number of Testimonials'), default=5)
speed_autoplay = models.PositiveIntegerField(
verbose_name=_('Speed of slider (milliseconds)'), default=3000)
picked_testimonials = models.ManyToManyField(Testimonials,
verbose_name=_('picked_testimonials'),
blank=True, null=True)
在编辑模式中,我可以查看我页面中的推荐,我可以毫无错误地发布,但是当我看到发布的页面时,推荐书没有显示。正在渲染插件模板,但picked_testimonials提供None
。这是模板:
<div class="max-width1440 block clearfix relative">
<div class="small-only-text-left small-12 small-offset-0 medium-text-center medium-offset-1 medium-10 large-offset-1 large-10 column pt-px60 pb-px40 pl-px40 pr-px40 slider-testimonials">
{% for testimonial in instance.picked_testimonials.all %}
{% if forloop.counter0 < instance.n_testimonials %}
<div class="slider column">
<blockquote class="acta_mediumitalic size36 pl-px80 pr-px80 line-height140">
{% render_model testimonial "description" %}
</blockquote>
<div class="mt-px30">
<p class="acta_book size20 softblack">{{ testimonial.author }},<span>{{ testimonial.city }}</span>
</p>
</div>
</div>
{% endif %}
{% endfor %}
</div>
</div>
答案 0 :(得分:4)
发布页面时,会创建一个插件副本 - 其中包含插件的字段,但不包含任何关系。 CMS中有一项规定正是为此目的提供复制方法,请参阅documentation中的示例:
class ArticlePluginModel(CMSPlugin):
title = models.CharField(max_length=50)
sections = models.ManyToManyField(Section)
def copy_relations(self, oldinstance):
self.sections = oldinstance.sections.all()
重要的一点是copy_relations,它确保新对象具有相同的关系链接。
在你的情况下,这些内容应该有效:
class TestimonialsPlugin(CMSPlugin):
n_testimonials = models.PositiveIntegerField(
verbose_name=_('Number of Testimonials'), default=5)
speed_autoplay = models.PositiveIntegerField(
verbose_name=_('Speed of slider (milliseconds)'), default=3000)
picked_testimonials = models.ManyToManyField(Testimonials,
verbose_name=_('picked_testimonials'),
blank=True, null=True)
def copy_relations(self, oldinstance):
self.picked_testimonials = oldinstance.picked_testimonials.all()