Search code examples
pythondjangoformssanitization

Sanitizing HTML in submitted form data


Is there a generic "form sanitizer" that I can use to ensure all html/scripting is stripped off the submitted form? form.clean() doesn't seem to do any of that - html tags are all still in cleaned_data. Or actually doing this all manually (and override the clean() method for the form) is my only option?


Solution

  • Django comes with a template filter called striptags, which you can use in a template:

    value|striptags
    

    It uses the function strip_tags which lives in django.utils.html. You can utilize it also to clean your form data:

    from django.utils.html import strip_tags
    message = strip_tags(form.cleaned_data['message'])