From 0e421711266fb6ab429e76b6e3af64a5cce9350a Mon Sep 17 00:00:00 2001 From: Mark Gregson Date: Fri, 10 Sep 2021 09:46:40 +1000 Subject: [PATCH] Mark cleaned data as template safe Fixes #27 --- django_bleach/forms.py | 7 +++++-- django_bleach/tests/test_forms.py | 7 +++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/django_bleach/forms.py b/django_bleach/forms.py index c0285b0..55d3039 100644 --- a/django_bleach/forms.py +++ b/django_bleach/forms.py @@ -5,6 +5,7 @@ from django.core.exceptions import ImproperlyConfigured from django.conf import settings +from django.utils.safestring import mark_safe from importlib import import_module from django_bleach.utils import get_bleach_default_options @@ -67,8 +68,10 @@ def __init__(self, allowed_tags=None, allowed_attributes=None, def to_python(self, value): """ - Strips any dodgy HTML tags from the input + Strips any dodgy HTML tags from the input. + + Mark the return value as template safe. """ if value in self.empty_values: return value - return bleach.clean(value, **self.bleach_options) + return mark_safe(bleach.clean(value, **self.bleach_options)) diff --git a/django_bleach/tests/test_forms.py b/django_bleach/tests/test_forms.py index af38d39..e5e4af4 100644 --- a/django_bleach/tests/test_forms.py +++ b/django_bleach/tests/test_forms.py @@ -1,7 +1,9 @@ # -*- coding: utf-8 -*- from django.test import TestCase +from django.utils.safestring import SafeString from mock import patch +from django_bleach.forms import BleachField from testproject.forms import BleachForm @@ -16,6 +18,11 @@ def test_empty(self): self.assertEqual(form.fields['no_tags'].to_python([]), []) self.assertEqual(form.fields['no_tags'].to_python({}), {}) + def test_return_type(self): + """ Test bleached values are SafeString objects """ + field = BleachField() + self.assertIsInstance(field.to_python("some text"), SafeString) + def test_bleaching(self): """ Test values are bleached """ test_data = {