如何在Django模型的TextField中使用静态文件?

时间:2019-06-11 16:51:08

标签: django django-models django-templates

我需要在模型的TextField中显示静态内容。

我曾尝试在模板中将TextField标记为安全,但是它似乎没有像其余模板标签那样解释它,只是将其显示为原始HTML。

从我的模板中

{{ project.content|safe }}

根据我的模型:

content = models.TextField()

在我看来:

class ProjectView(generic.DetailView):
    model = Project
    context_object_name = "project"
    template_name = "projects/project.html"

我希望内容({% static "wdv101/koala/index.html" %})显示为静态内容的url,但它显示为{%static“ wdv101 / koala / index.html”%}

1 个答案:

答案 0 :(得分:0)

您要实现的目标是使用字符串或project.content作为模板。将其标记为保存表示例如Javascript不会被转义,所以我将被执行。 您可以使用custom template tag解决您的“问题”,该问题将您的内容变量作为输入,将其呈现并返回呈现的html。

自定义模板标签:

from django import template
from django.template import Template
from django.utils.html import mark_safe

register = template.Library()

@register.simple_tag(takes_context=True)
def in_template_renderer(context, template_string):
   template = Template(template_string)
   return mark_safe(template.render(context))

在模板中使用它:

{% load in_template_renderer %}

{% in_template_renderer project.content %}

不要忘记在project.content中加载所需的模块,例如“ static”。

相关问题