Skip to content

Select2 Dropdown Updates based on Forwarded field Correctly, But Selected Value Does Not always Display Correctly in Input Box #1394

@hrhktkbzyy

Description

@hrhktkbzyy

Hi,

When the content_type field changes, the object_id dropdown updates correctly based on the selected content type. However, when an item is selected from the updated dropdown, the input box does not reflect the selected value. The selected value is not displayed in the input box after choosing from the dropdown.

Steps to Reproduce:

  • Change content_type to A (e.g., A, B, C). The object_id dropdown updates with relevant options based on the content_type.
  • Select an option from the object_id dropdown. (e.g. A1), A1 was in the input box.
  • Change content_type to B. The object_id dropdown was updated. (e.g. B1, B2), when select B1, the input box will still be A1 (A1 and B1 share the exact same id number like 1). If I select B2, B2 is correctly SELECTED into the input box.

Expected Behavior:
The input box should display the selected value from the dropdown after an item is chosen.

Actual Behavior:
The dropdown updates correctly, but the input box does not display the selected item.

Code demo

class TestForm(forms.ModelForm):
    content_type = forms.ModelChoiceField(
        queryset=ContentType.objects.filter(model__in=['A', 'B', 'C']),
        widget=autocomplete.ModelSelect2(url='content-type-autocomplete'),
    )

    object_id = forms.IntegerField(
        widget=autocomplete.Select2(url='object-id-autocomplete', forward=('content_type',)),
    )

## view

class ContentTypeAutocomplete(LoginRequiredMixin, autocomplete.Select2QuerySetView):
    """Autocomplete view for ContentType selection"""

    def get_queryset(self):
        # Limit to game app models: Season, GameLeague, Game
        qs = ContentType.objects.filter(
            app_label='game',
            model__in=['A', 'B', 'C']
        )

        if self.q:
            qs = qs.filter(model__icontains=self.q)

        return qs

    def get_result_label(self, item):
        # Display model name in a more user-friendly format
        return item.model.capitalize()


class ObjectAutocomplete(LoginRequiredMixin, autocomplete.Select2QuerySetView):
    """Autocomplete view for generic object selection based on content type"""

    def get_queryset(self):
        # No content type selected yet
        content_type_id = self.forwarded.get('content_type', None)
        if not content_type_id:
            return None

        try:
            content_type = ContentType.objects.get(id=content_type_id)
            model = content_type.model_class()

            # Get valid objects of this model
            model_filters = {}
            if hasattr(model, 'status'):
                model_filters['status'] = BaseModel.STAT_VALID

            qs = model.objects.filter(**model_filters)

            # Filter by search term if provided
            if self.q:
                # Try to search by name or other common fields
                search_fields = ['name', 'short_name', 'title']
                query = Q()
                for field in search_fields:
                    if hasattr(model, field):
                        query |= Q(**{f'{field}__icontains': self.q})

                if query:
                    qs = qs.filter(query)

            return qs

        except (ContentType.DoesNotExist, AttributeError):
            return None

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions