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 formfield() does not honor model field blank attribute making form field always required #21

Closed miki725 closed 3 years ago

miki725 commented 3 years ago

Describe the bug

When blank=True is set to True, expected field.formfield() should be required=False however that is not honored.

To Reproduce

Steps to reproduce the behavior:

  1. Create model
  2. Add bleached field with blank=True
  3. Add it to django admin
  4. Check in django admin if field is required

Expected behavior

It should appear as not required but it appears as required

Context

Looks like its related to https://github.com/marksweb/django-bleach/blob/0dfcd6de5cbd3719e461f840fcf3b54c5a7fd8b8/django_bleach/models.py#L37-L47

Recently it was changed to return BleachField which inherently does not call super() where base Field correctly interprets other django model field attributes such as blank:

https://github.com/django/django/blob/56f9579105c324ff15250423bf9f8bdf1634cfb4/django/db/models/fields/__init__.py#L908-L914

(copy from link since it does not render inline)

    def formfield(self, form_class=None, choices_form_class=None, **kwargs):
        """Return a django.forms.Field instance for this field."""
        defaults = {
            'required': not self.blank,
            'label': capfirst(self.verbose_name),
            'help_text': self.help_text,
        }
marksweb commented 3 years ago

Good catch @miki725 thanns for raising 👍

Are you able to contribute a fix for this?

I've added a couple of tests to check the required flag on 2 fields. Will see if I have chance to fix.