Skip to content

🐛 Defining 'attrs' and 'data_view' as classes var on a custom widget doesn't doesn't work #337

@coredumperror

Description

@coredumperror

Bug Description

Given that the docs say you can specify search_fields via both class vars on a custom widget subclass, and as constructor kwargs to a base widget class (e.g. ModelSelect2Widget), and that looking at the code shows that you can do the same for model and queryset, I assumed the same could be done for attrs and cata_view.

But it can't. Any attrs class var gets overwritten by {}, due to what I believe qualifies as a bug in HeavySelect2Mixin, and data_view gets overwritten by a bug in ModelSelect2Mixin.

Steps to Reproduce

  1. Define a custom Heavy widget class with an attrs and data_view class variable, e.g.:
class UsersWidget(s2forms.ModelSelect2Widget):
    search_fields = [
        "last_name__icontains",
        "first_name__icontains",
    ]
    attrs = {
        "data-placeholder": "Search for users by name...",
        "data-close-on-select": "false",
        "data-width": "50%",
    }
    data_view = "my_data_view"

  1. Use that Widget class in your Form.
  2. Notice that the attrs are not applied in the HTML, and the data_view is not used to build the select list (the "auto" view is used instead).

Expected Behavior

I expected an attrs and data_view class vars to apply themselves in the same way that an attrs and data_view kwarg on the Widget's constructor would, but they instead have no effect.

This happens because if there is no attrs constructor kwarg, HeavySelect2Mixin explicitly sends None as the attrs kwarg to super().__init__(), which eventually gets to Widget.__init__(), which sets self.attrs to {}, overwriting the original class var before it can be used by Widget.get_context(), which sends it to Widget.build_attrs().

The data_view problem happens in ModelSelect2Mixin.__init__(), where it sets defaults['data_view'] to "django_select2:auto-json", never even trying to read the data_view class var to get the value.

This makes it impossible to create canned Widget classes with a custom attrs or data_view for use by multiple different forms, since the only way to specify attrs and data_view is via kwarg.

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions