解码"用于Django中的图像和链接

时间:2017-08-07 05:08:47

标签: html django postgresql ckeditor

对于我正在编写的Django应用程序,我正在使用Postgres数据库并在所述数据库中存储CKEditor输出。

链接存储如下:<a href=&quot;http://google.com&quot;>google</a>

图像存储如下:<img src=&quot;https://latex.codecogs.com/gif.latex?%5Cfrac%7Ba%7D%7Bb%7D&quot; />

在模板中,我使用安全标记输出此html以及数据库中其余存储的内容:{{post.content |safe}}

Chrome看到href和src没有&#34;标记并将其添加到&quot;左右,导致href=""http://google.com""导致各种问题。

有关如何解决此问题的任何想法?我是否需要使用CKEditor来存储未转义的引号?我应该添加模板标签或javascript函数来替换所有这些编码的引号吗?

2 个答案:

答案 0 :(得分:0)

使用模板标记修复了Arpit建议的问题。

local   all             postgres                                peer

在模板中:

## app/templatetags/unescape_quotes.py ##

from django import template

register = template.Library()

@register.filter
def unescape_quotes(s):
    html_codes = (
            ('"', '&quot;'),
        )
    for code in html_codes:
        s = s.replace(code[1], code[0])
    return s

它只是一个s.replace但写的,以便我以后可以通过添加代码来更多地删除html。

答案 1 :(得分:0)

不要首先存储实体。将'entities': False,放入CKEditor配置中。

现在您的所有新数据都将正确存储。要修复旧数据,您应该编写数据迁移。 https://docs.djangoproject.com/en/1.11/topics/migrations/#data-migrations

使用python manage.py makemigrations --empty appname创建空迁移。并使用migrations.RunPython(your_data_migration)处理数据。

该函数可以包含一个简单的replace('&quote', '"')或使用HTMLParser,如本答案中所示:Decode HTML entities in Python string?