Skip to content

🐛 Custom attributes defined in result_from_instance are not present for default value #308

@tomas-nz

Description

@tomas-nz

Bug Description

Method result_from_instance is not called for a default (initial) value. Only method label_from_instance is called in this case.

Steps to Reproduce

If I define a custom widget:

class MyWidget(s2forms.ModelSelect2Widget):
    model = MyModel
    queryset = MyModel.objects.all()
    
    def result_from_instance(self, obj, request):
        return {
            'id': obj.pk,
            'text': self.label_from_instance(obj),
            'my_extra': obj.extra_attribute,
        }

Then I define a form field with an initial value:

my_field = forms.ModelChoiceField(widget=MyWidget, initial=MyModel.objects.get(pk=123))

In JavaScript in the browser I look at the selected value with:

$('#id_my_field').select2('data')[0]

I expect to see attribute my_extra but it is not there, only id and text are. Once I select a different value from the options list, then my extra attribute shows up correctly.

Expected Behavior

I would expect that result_from_instance would be called and my extra attribute would be present when an unchanged default value is queried using $('#id_my_field').select2('data')[0]

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