Allowing basic html markup in django

霸气de小男生 提交于 2019-12-10 16:33:54

问题


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 }} or {% autoescape off %}

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 }}

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.


UPDATE

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.


回答1:


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.



来源:https://stackoverflow.com/questions/18048530/allowing-basic-html-markup-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!