applegrew / django-select2

This is a Django integration for Select2

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Select2Widget ignores empty_label

dyve opened this issue · comments

Describe the bug
When using Select2Widget on a field that has empty_label set, the empty_label setting is ignored. I would expect the content of empty_label (if any) as the default value for data-placeholder in the attrs of select2Widget.

Code Snippet

class BookForm(forms.ModelForm):
    """Model Book has field user that is ForeignKey to User."""
    class Meta:
        model = Book
        fields = ["user"]
        widgets = {"user": Select2Widget}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["user"].empty_label = "No user is fine too."
        # self.fields["user"].widget.attrs['data-placeholder'] = self.fields["user"].empty_label
        # Uncomment the line above to make the empty_label appear as the placeholder

To Reproduce
Steps to reproduce the behavior:

  1. Use the form from the example.
  2. See that "No user is fine too." does NOT appear.
  3. Uncomment the line that enables the workaround.
  4. See that "No user is fine too." DOES appear.

Expected behavior
When a field has an empty_label, I expect that to be the default value for Select2Widget.attrs["data-placeholder"]

Hi @dyve very good catch, this seems to be a bug in deed. I believe the problem is here:

default_attrs['data-placeholder'] = ''

as well as here:
self.choices = list(chain([('', '')], self.choices))

and here:
default[1].append(self.create_option(name, '', '', False, 0))

The solution is simple. Instead of using an empty string, this should point to self.empty_label.
Would you be interested in providing a pull-request that patches the issue? I would really welcome the support.

Best
-Joe

I went ahead and wrote a patch myself, to make sure this feature reaches users asap. Thanks!

Released in 7.1.1, thx!