python - 如何在 django cms 页面模板上显示 django 模型数据
问题描述
我希望能够在 django cms 页面上使用我的外部应用程序数据。我可以使用自定义插件数据,但不能使用来自普通 django 应用程序的数据
我尝试创建视图来处理我的数据,但是如何从 django cms 页面调用此视图? 这正是我所要求的,但他的解释很肤浅,答案中提供的链接不再使用。
这是我的模型:
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
部分
我希望在模板中显示来自我的模型的数据。
解决方案
我能够通过执行以下操作来实现这一点:
@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
)的相关文章添加到上下文中
推荐阅读
- mustache - 如果循环不是数组中的最后一项,使用车把模板是否可以呈现逻辑?
- java - 如何转换这样的json响应?
- excel - 为什么在对 VBA 宏应用更改后索引不刷新?
- amazon-web-services - Spark SQL 查询以获取在 AWS S3 中存储为 CSV 的 Athena 表的最后更新时间戳
- spring-boot - 为什么亚洲地区的 GCP Dataflow 作业需要比欧洲地区更多的时间来启动 - 过程 - 停止
- flutter - 如果我没有什么可返回的,返回后在颤振小部件中放什么
- reactjs - 在 React 中设置下拉菜单的默认值
- algorithm - 在 f(n)=n 阶乘的情况下如何使用主方法或递归问题
- python - python中数组中的线性回归
- python - 如何将两个 json 列表合并到一个数据框中?