Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 756
abolotnov Avatar asked Apr 12 '11 21:04

abolotnov


People also ask

How do you sterilize form data?

Sanitizing data can be done by removing or replacing contextually-dangerous characters, such as by using a whitelist or escaping the input data. While it may not be intuitive, even data that a user submits to their own area on a site should be validated.

How do you disinfect HTML?

Sanitize a string immediatelysetHTML() is used to sanitize a string of HTML and insert it into the Element with an id of target . The script element is disallowed by the default sanitizer so the alert is removed.

What is form sanitization?

to sanitize a document before releasing it to the press. In real world sanitize is to “clean” anything from “bad things”. In computer sciences it means the same thing. Mostly for security purposes, we protect the system from malicious data. For example, a user can type anything in an input form and submit it.

What's the importance of sanitizing input data?

Input sanitization ensures that the entered data conforms to subsystem and security requirements, eliminating unnecessary characters that can pose potential harm.


2 Answers

strip_tags actually removes the tags from the input, which may not be what you want.

To convert a string to a "safe string" with angle brackets, ampersands and quotes converted to the corresponding HTML entities, you can use the escape filter:

from django.utils.html import escape message = escape(form.cleaned_data['message']) 
like image 158
simao Avatar answered Oct 14 '22 13:10

simao


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']) 
like image 20
Bernhard Vallant Avatar answered Oct 14 '22 15:10

Bernhard Vallant