Skip to content

Instantly share code, notes, and snippets.

@lambdaman2
Created October 1, 2012 12:48
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lambdaman2/3811586 to your computer and use it in GitHub Desktop.
Save lambdaman2/3811586 to your computer and use it in GitHub Desktop.
Django: Strip/Remove HTML tags (django utils)
# To strip/remove HTML tags from an existing string we can use the strip_tags function.
# import the strip_tags
from django.utils.html import strip_tags
# simple string with html inside.
html = '<p>paragraph</p>'
print html # will produce: <p>paragraph</p>
stripped = strip_tags(html)
print stripped # will produce: paragraph
# This is also available as a template tag:
{{ somevalue|striptags }}
# If you want to remove only specific tags you need to use the removetags
from django.template.defaultfilters import removetags
html = '<strong>Bold...</strong><p>paragraph....</p>'
stripped = removetags(html, 'strong') # removes the strong only.
stripped2 = removetags(html, 'strong p') # removes the strong AND p tags.
# Also available in template:
{{ value|removetags:"a span"|safe }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment