如何在django cms页面模板上显示django模型数据

时间:2019-04-12 09:18:08

标签: python django django-templates django-cms

我希望能够在django cms页面上使用我的外部应用程序数据。 我可以使用自定义插件数据,但不能使用普通django应用程序中的数据

我尝试创建用于处理数据的视图,但是如何从Django cms页面中调用此视图? here正是我所要的,但他的解释很浅,答案中提供的链接不再使用。

这是我的模特:

class ExternalArticle(models.Model):
    url = models.URLField()
    source = models.CharField(
        max_length=100,
        help_text="Please supply the source of the article",
        verbose_name="source of the article",
    )
    title = models.CharField(
        max_length=250,
        help_text="Please supply the title of the article",
        verbose_name="title of the article",
    )
    class Meta:
        ordering = ["-original_publication_date"]

    def __str__(self):
        return u"%s:%s" % (self.source[0:60], self.title[0:60])

我的模板具有占位符

{% load cms_tags %}

{% block title %}{% page_attribute "page_title" %}{% endblock title %}

{% block content %}
    <section class="section">
        <div class="container">

             <div class="row">
                    <!-- header-->
                    <div class="col-lg-12">
                        <div class="updates">                           
                           {% placeholder "header" %}                         
                        </div>
                    </div>
                    <!-- header end-->

            </div> <!-- end row --> 

但我不介意在占位符内无法在模板上的任何位置显示此数据 我有一个在Django cms中使用的自定义页面。 我想显示以上数据是Django cms页面中的一部分 如果此模型是从CMSPlugin继承的,那将很容易,因为我可以在占位符中使用自定义插件

我希望在模板中显示我的模型中的数据。

3 个答案:

答案 0 :(得分:0)

  {% load cms_tags %}
<h1>{{ instance.poll.question }}</h1>

<form action="{% url polls.views.vote poll.id %}" method="post"> {% csrf_token %} 
        {% for choice in instance.poll.choice_set.all %}
          <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
          <label for="choice{{ forloop.counter }}">{{ choice.choice }}</label><br /> 
         {% endfor %} 

          <input type="submit" value="Vote" /> 
</form>

答案 1 :(得分:0)

您必须以某种方式将ExternalArticle与页面对象连接。例如

答案 2 :(得分:0)

我能够做到以下几点:

@plugin_pool.register_plugin
class ArticlesPluginPublisher(CMSPluginBase):
    model = ArticlesPluginModel
    name = _("Articles")
    render_template = "article_plugin/articles.html"
    cache = False

    def render(self, context, instance, placeholder):
        context = super(ArticlesPluginPublisher, self).render(
            context, instance, placeholder
        )
        context.update(
            {
                "articles": Article.objects.order_by(
                    "-original_publication_date"
                )
            }
        )
        return context

插件模型(ArticlesPluginModel)仅用于存储插件实例的配置。不是实际的文章。 然后,渲染将只是将来自外部应用程序(Article)的相关文章添加到上下文中。