【问题标题】:simple loop in rendered template django cms plugin渲染模板 django cms 插件中的简单循环
【发布时间】:2017-03-29 06:37:36
【问题描述】:

我想在渲染模板中循环从数据库中获取的数据。使用 cms 插件。 我在 html 模板中循环数据没有问题。但是,如果我使用 CMSPlugin 在占位符中插入新应用程序,则没有任何显示。

如果我运行 url localhost:port/test.html。我得到了我想要的输入。但是渲染的模板不会循环数据。

{% for post in posts %}
   {{ post.firstoption }}
{% endfor %}

如果我使用下面的代码,我的渲染模板中不会显示任何内容。值在呈现的模板中传递。因为,如果我尝试 {{instance.firstoption}} 我会得到模板中显示的值。问题是我不能用标签实例循环数据。

{% for post in instance.posts %}
  {{ post.firstoption }}
{% endfor %}

我也试过{% for post in instance.posts_set.all %}{% for post in instance.posts.all %}

cms_plugins.py

class pricing(CMSPluginBase):
    model = mymodel
    name = _("myplugin")
    render_template = "template.html"
    cache = False

    def render(self, context, instance, placeholder):
        context.update({'instance': instance})
        return context

models.py

class mymodel(CMSPlugin):
    firstoption = models.CharField(max_length=200)


        def __str__(self):
    return self.firstoption

【问题讨论】:

  • 如果没有对instance 模型、视图或其他任何相关内容的任何描述,很难说会出现什么问题。请尝试制作minimal reproducible example
  • 我可以将我的视图和 cms 插件粘贴给你。但事实是 {{instance.something}} 有效。我只想知道如何用实例制作 for 循环。我在帖子中编辑并粘贴了更多代码
  • 为初学者和模型添加您的视图
  • 你需要展示你的模型。
  • 显示代码中定义的模型“mymodel”的代码。

标签: python django django-templates django-cms


【解决方案1】:

这可能是因为你需要在你的帖子上调用all

{% for post in instance.posts.all %}
  {{ post.firstoption }}
{% endfor }

【讨论】:

  • 嘿,我以前试过这个,但没有用。我也试过 {% for post in instance.posts_set.all %}
  • @PrakharTrivedi 很好发现。应该是{{
  • 错字错误。实际上我得到了{{。我编辑了帖子。感谢您帮助我
猜你喜欢
  • 2016-08-14
  • 2020-08-11
  • 2015-10-29
  • 1970-01-01
  • 1970-01-01
  • 2013-10-10
  • 2017-10-26
  • 2011-06-12
  • 1970-01-01
相关资源
最近更新 更多