在django中允许基本的html标记 [英] Allowing basic html markup in django

查看:133
本文介绍了在django中允许基本的html标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个将处理用户提交内容的应用程序。我希望使用户能够使用基于文本的内容看起来很漂亮,基本的html标记, i>< b>< br>。但是我确实想阻止他们使用脚本标签。 Django会自动转义所有内容,因此它也会禁用所有安全标记。我可以通过使用以下方式来禁用此功能:

Im creating an app that will process user submitted content. I would like to enable users to make their text-based content look pretty with basic html markup i.e < i > < b > < br > . However I do want to prevent them from using things like script tags. Django will auto escape everything therefore it will also disable all safe markup. I can disable this by using:

{{somevar | safe}} %autoescape off%}

但是,这也将启用所有harmfull脚本标签。 Django确实提供了linebreaks过滤器标签,它将白色空间转换为br或p标签,同时保持html的安全:

However this will also enable all harmfull script tags. Django does provide the linebreaks filter tag which transform white space to br or p tags while keeping the html safe:

{{ somevar|linebreaks }}

不幸的是,我不知道允许使用b或i标签的任何筛选器。

Unfortunately I am not aware of any filters that allow b or i tags to be used.

所以我想知道是否有一个聪明的解决方案这个问题。如果您建议第三方库最好在保存模型或呈现内容时使用该解决方案。

So I am wondering if there is a smart solution to this problem. And if you suggest a third party library would it be best to employ the solution when saving the model or when rendering the content.

最后我用这个解决方案去了一个 Python HTML消毒剂/洗涤器/过滤器。后一个答案提供了一种使用美丽的图库从用户提交的内容中删除所有不需要的HTML标签的方法。这可以在保存模型之前完成,因此在渲染页面时可以安全地使用模板过滤器 {{somevar | safe}}

In the end I went with this solution Python HTML sanitizer / scrubber / filter. This latter answer provide a way to use the Beautiful Soup library to remove all unwanted html tags from user submitted content. This can be done before saving the model therefore making it safe to use the template filter {{ somevar|safe }} when rendering the page.

推荐答案

看看 Django的TinyMCE的。它应该给你你想要的灵活性。在进入数据库之前,您将彻底消毒内容。 TinyMCE可以配置为允许或不允许任何您想要的标签。

Take a look at django-tinymce. It should give you the flexibility you're looking for. You're going to be safest sanitizing the content before it makes its way into your database. TinyMCE can be configured to allow or not allow whatever tags you'd like.

这篇关于在django中允许基本的html标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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