Django 模板中的变量以双引号显示

Dea*_*ool 3 python django django-templates

我从我的Post模型中获取数据并简单地传递到模板中。但是输出显示在双引号中。我的 Post 模型中有 html 标签,它不是渲染而是显示为代码。

视图.py

# It display the single post
def single_post(request,cat,post_id,post_title):
    single_post = Post.objects.get(pk = post_id)
    return render(request, 'blog/single_post.html', {'single_post': single_post})
Run Code Online (Sandbox Code Playgroud)

single_post.html

<h1>I'm single post page</h1>

{{single_post.title}}

<br>
<br>
{{single_post.content}}
Run Code Online (Sandbox Code Playgroud)

浏览器输出

在此处输入图片说明 在此处输入图片说明

我的数据库中的数据 在此处输入图片说明

sha*_*ker 5

在你的截图中,我没有看到双引号,我看到了 HTML 标签。如果您在内容中输入 HTML,而不是让不受信任的用户输入它,那么您应该考虑将其呈现到页面上是安全的(您不太可能发布恶意的 javascript,或者用错误的 HTML 搞砸您的布局,对吧?)。因此你想safe在你的内容上使用 Django 的过滤器:

{{single_post.content|safe}}
Run Code Online (Sandbox Code Playgroud)

这将允许解释而不是呈现输入和存储的 HTML。

  • 我从事网络开发很长时间了。在我生命中的今天,我开始知道。再次感谢。 (2认同)