marksweb / django-bleach

Bleach is a Python module that takes any HTML input, and returns valid, sanitised HTML that contains only an allowed subset of HTML tags, attributes and styles. django-bleach is a Django app that makes using bleach extremely easy.
MIT License
148 stars 23 forks source link

Model field formfield method raises exception if passed a form_class argument #25

Closed MrkGrgsn closed 3 years ago

MrkGrgsn commented 3 years ago

Describe the bug The model field formfield method raises an exception if passed a form_class argument:

   File "ve/lib/python3.6/site-packages/django_bleach/models.py", line 47, in formfield
    return forms.BleachField(**kwargs)
  File "ve/lib/python3.6/site-packages/django_bleach/forms.py", line 51, in __init__
    super(BleachField, self).__init__(*args, **kwargs)
  File "ve/lib/python3.6/site-packages/django/forms/fields.py", line 214, in __init__
    super().__init__(**kwargs)
TypeError: __init__() got an unexpected keyword argument 'form_class'

This prevents overriding the form field used for a BleachField model field in model forms.

To Reproduce The bug can be reproduced by instantiating a model form and overriding the default form field class for a bleach model field:

class MyModel(Model):
    bleached = models.BleachField(...)

class MyBleachFormField(forms.BleachField):
    ...

class MyModelForm(ModelForm):
    class Meta:
        model = MyModel
        field_classes = {"bleached": MyBleachFormField}

Expected behavior I expect the form_class argument to be used the same way it is by core Django model fields, ie, it overrides the default form field. See the base definition of formfield.

Additional context This bug impacts my project because the project uses a custom form field, a child of BleachField that marks the submitted value in cleaned_data as template safe so it can be used in templates without having to explicitly mark it as safe (we try to avoid ad-hoc calls to mark_safe in our codebase). The use case is a django-formtools wizard confirmation page, where the wizard renders the submitted form values to the page for the user to check before the forms are saved and committed.

I'm happy to write a patch.

marksweb commented 3 years ago

@MrkGrgsn if you could raise a PR for this then that would be appreciated 👏