Search code examples
djangoformssanitization

Use bleach to Sanitize all Form input fields in Django


I am new to sanitize input fields in django form and need your help. Here is one example for bleaching one field in django form. http://www.agmweb.ca/2010-12-31-django-and-bleach/

My question is, if there are 10 such fields in django ModelForm, is there a better way than bleaching all 10 fields ONE by ONE?

That is, could it just use something like this bleach(form.data)?


Solution

  • Use django-bleach which provides a BleachField (wrapper around models.TextField):

    from django import models
    from django_bleach.models import BleachField
    
    class Post(models.Model):
    
        content = BleachField()
    

    Or if you want to bleach all fields of your form you could override _clean_fields():

    class YourForm(ModelForm):
    
        def _clean_fields(self):
            super(LogCollectorParamsForm, self)._clean_fields()
            for name, value in self.cleaned_data.items():
                self.cleaned_data[name] = bleach.clean(value)