Django: allow user to submit valid HTML in form field

With Django, is it possible for users to submit HTML in a form field, save it and then display the HTML in a template?

For example, a user adds a link to a text field, which should then appear as a tag in the rest of the text.

The user enters something like:

this is a site called <a href="http://stackoverflow.com">SO</a>. 

The SO link will be a link instead of rendering as text.

+6
source share
2 answers

By default, Django is removed. You can mark a string as safe through a filter or tag to prevent auto-escaping behavior.

 {{ my_text_with_html|safe }} {% autoescape off %} {{ my_test_with_html }} {% endautoescape %} 

If you accept the html entered by the user, you will want to sanitize it so that they cannot write scripts, etc. To do this, simply search for python html and apply it before sending data to the template.

Python HTML sanitizer / scrubber / filter

+11
source

You can say that Django HTML is safe by marking it with the appropriate filter :

 {{ variable|safe }} 

You can also use the autoescape tag to disable auto-escaping:

 {% autoescape off %} {{ variable }} {% endautoescape %} 

However, if you enable this feature for other (unknown) users, I highly recommend using something else, since HTML can be pretty painful for properly disinfecting from Javascript or other HTML things that you don't need (e.g. * arguments, etc.). Django actually provides basic support for some markup languages that you can provide to your users. I think markdown is the most popular.

+3
source

Source: https://habr.com/ru/post/917307/


All Articles