Skip to main content
 首页 » 编程设计

python之Django 模板中的变量显示在双引号中

2024年09月07日27powertoolsteam

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

views.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}) 

single_post.html

<h1>I'm single post page</h1> 
 
{{single_post.title}} 
 
<br> 
<br> 
{{single_post.content}} 

Browser Output

Data in my Database

请您参考如下方法:

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

{{single_post.content|safe}} 

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