best_filters.sanitizetags¶
Remove all tags that is not in the allowed list
Argument should be in form ‘tag1:attr1:attr2 tag2:attr1 tag3’, where tags are allowed HTML tags, and attrs are the allowed attributes for that tag.
In the example above, it means accepted tags are : <tag1 attr1=”…” attr2=”…”> and <tag2 attr1=”…”> and <tag3> All other HTML tags an attributes will be removed.
for example <tag2 attr1=”…” attr3=”…”> <tag4 …> will be replaced by just <tag2 attr1=”…”>
The filter also unconditionnaly removes attributes having values starting with ‘javascript:’ to avoid malicious code.
If No argument is given, the filter will look for SANITIZETAGS_ALLOWED in settings or will use this default value: ‘a:href:name b u p i h1 h2 h3 hr img:src table tr td th code’
Notes
- The output is marked as a safe string.
- If the HTML given has not a correct syntax, an error html message is displayed instead of the original value.
- Only tags are sanitized, not the text in between
Examples
>>> c = {'comment':'''<a href="x" name="y" id="z"></a> <b></b> <u></u> ... <p></p> <i></i> <h1></h1> <h2></h2> <h3></h3> <hr> ... <img src="x" id="y"> <table></table> <tr></tr> <td></td> <th></th> ... <code></code> <unkown_tag></unknown_tag> <div></div>'''} >>> t = '{% load best_filters %}{{ comment|sanitizetags}}' >>> print(Template(t).render(Context(c))) <a href="x" name="y"></a> <b></b> <u></u> <p></p> <i></i> <h1></h1> <h2></h2> <h3></h3> <hr/> <img src="x"/> <table></table> <tr></tr> <td></td> <th></th> <code></code>
>>> c = {'comment':'My comment <b>with</b> <a href="spam">ads</a>'} >>> t = '{% load best_filters %}{{ comment|sanitizetags:"B u i"}}' >>> Template(t).render(Context(c)) 'My comment <b>with</b> ads'
>>> c = {'comment': ... '<i>Go</i> <a badattrib="xx" href="google.com">here</a>'} >>> t = '{% load best_filters %}{{ comment|sanitizetags:"a:href"}}' >>> Template(t).render(Context(c)) 'Go <a href="google.com">here</a>'
>>> c = {'comment':'<b><i><u>nested tags</u></i></u>'} >>> t = '{% load best_filters %}{{ comment|sanitizetags:"b u"}}' >>> Template(t).render(Context(c)) '<b><u>nested tags</u></b>'
>>> c = {'comment':'''<a href="javascript:hack_me();" name="iambad"> ... <a href="http://google.com" name="iamgood">'''} >>> t = '{% load best_filters %}{{ comment|sanitizetags:"a:href:name"}}' >>> Template(t).render(Context(c)) '<a name="iambad">\n<a href="http://google.com" name="iamgood"></a></a>'