4

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.

Community
  • 1
  • 1
Niels
  • 1,513
  • 3
  • 20
  • 29

1 Answers1

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.

Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
  • 1
    This works very well however I have several ways to submit data to the server. In some of these cases TinyMCE integration is not an option. – Niels Aug 07 '13 at 16:37
  • Beautiful Soup will certainly work. Glad you got it figured out. – Brandon Taylor Aug 07 '13 at 17:43
  • django-tinymce is an input editor. The question is in regards to escaping the output to the user, not the input to the database. – kloddant Jul 03 '18 at 13:59