如何从Django数据库将模板标签解释/呈现为HTML [英] How to interpret/render template tags as HTML from Django database

查看:32
本文介绍了如何从Django数据库将模板标签解释/呈现为HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加来自Django管理站点的带有图片的帖子,但是安全/自动转义过滤器无法解释Django的模板标签.

I'm trying to add posts with images from Django admin site, but the safe/autoescape-off filter cannot interpret Django's template tags.

我的输入和页面如下所示:

My input and page look like:

复制图片地址"给出了 http://127.0.0.1:8000/%7B %% 20static%20 'post/image.jpg'%20 %% 7D

"copy image address" gives http://127.0.0.1:8000/%7B%%20static%20'post/image.jpg'%20%%7D

我的视图继承自通用ListView.

My view inherits from a generic ListView.

我的base.html和post_list.html:

My base.html and post_list.html:

<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div style="color: red;">
      <a href="{% url 'admin:index' %}">admin</a>
      {% block contents %}
      {% endblock %}
    </div>
  </body>
</html>

{% extends 'post/base.html' %}
{% block contents %}
{% for post in object_list %}
  {% autoescape off %}{{ post.text }}{% endautoescape %}
  {{ post.text|safe }}
{% endfor %}
{% endblock %}

推荐答案

您无法直接在模板中执行您要执行的操作.Django模板由节点"组成,这些节点随后解析为字符串.使用 {{variable}} 语法的节点总是返回一个字符串:即使您使用 safe 过滤器,Django也不会尝试转换您的 post.text 字符串放入模板引擎要渲染的节点中.

You can't do what you're trying to do directly in the template. Django templates are made up of "nodes" that are later resolved into strings. Nodes using the {{ variable }} syntax always return a string: even if you use the safe filter, Django will not try to convert your post.text string into nodes to be rendered by the templating engine.

您可以通过手动将文本呈现为Django模板来在视图中解决此问题:

You could potentially work around this in the view by manually rendering your text as a Django template:

from django.template import Template

class MyListView(ListView):

    #...your existing code

    def get_context_data(self, **kwargs):
        context = super(MyListView, self).get_context_data(**kwargs)
        for post in context["object_list"]:
            post.rendered_text = Template(post.text).render(context)
        return context        

然后在您的模板中:

{% for post in object_list %}
    {{ post.rendered_text|safe }}
{% endfor %}

但是要当心!从安全角度来看,这是一个非常糟糕的主意! safe 标签已经非常危险,因为它允许跨站点脚本攻击:有权创建帖子的任何人都可以注入向用户显示的恶意Javascript.这个额外的渲染步骤更加危险,因为它还允许访问Django模板语言和视图的所有上下文,而这些上下文可以访问服务器端的机密.

But beware! This is a pretty bad idea from a security standpoint! The safe tag is already quite dangerous because it allows cross-site scripting attacks: anyone who has access to create a post can inject malicious Javascript that is displayed to the user. This extra rendering step is even more dangerous because it also gives access to the Django templating language and all the context of your view, which could have access to server-side secrets.

这篇关于如何从Django数据库将模板标签解释/呈现为HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆