python - 在 TextField 中呈现 Django 应用程序

标签 python django

我正在创建一个应用程序来显示文章。在我的模型中,我有一个包含文章内容的 TextField。

现在我希望能够在我的文章中呈现另一个应用程序。假设我有一个投票应用程序,我想在文章中间显示一个投票。我该怎么做?

我尝试在帖子中放置一个 {% render_poll 42 %},但正如预期的那样,它只会在生成的页面中显示它。

我是否应该创建某种标记(比如 [poll=42])并在显示呈现的 html 页面之前解析它? (我使用 markdown 库,也许我可以扩展它。)我怎样才能保持良好的“django 友好”方式?我希望在管理面板中时,我可以轻松地在文章中插入民意调查(或其他应用程序)。

最佳答案

你可以 compile TextField 字符串作为模板。即:

from django.db import models
from django.template import Template, Context


class YourModel(models.Model):
    body = models.TextField()

    def render_body(self, context=None):
        template = Template(self.body)
        context = context or {}
        context['object'] = self
        return template.render(Context(context))

然后在实际模板中,您可以使用 {{ your_model.render_body }} 而不是 {{ your_model.body }}

关于python - 在 TextField 中呈现 Django 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11447972/

相关文章:

python - 在 Django 中渲染数据库中的自定义模板标签

python - 属性错误 : 'tuple' object has no attribute 'get' in Django

python - 如何删除字典多个元组中的重复项?

python - Django 中已弃用的包语法

python - Django 压缩器抛出字典更新序列元素 #0 的长度为 9;需要 2 个

django - 在一个页面上使用多个不同的表单(Django 1.7 中的 Crispyforms)

python - C++11 正则表达式混淆

python - sympy 的plot_parametric 说 TypeError : can't convert complex to float

python - 保持 OrderedDict 内元素的顺序

arrays - 使用 Django 过滤 ArrayIngerField