[Answered ]-Django Select2MultipleWidget leads to form continuously trying to load

1👍

You can empty the pm_f4_events field’s choices in the __init__ method:

class PMForm(forms.ModelForm):
    class Meta:
        model = ToolPm
        fields = ['wafer_handling', 'wafer_based', 'handling_type', 'pm_f4_events']
        widgets = {
            'handling_type': forms.CheckboxSelectMultiple,
            'pm_f4_events': s2forms.ModelSelect2MultipleWidget(
                model=F4Events, 
                search_fields=["name__icontains",],
                attrs = {'data-placeholder': 'Please Choose F4 Events'}
            )
         }


    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        choices_F4Events = []
        pm_f4_events_field = self.fields["pm_f4_events"]
        # selected values
        selected_F4Events = self.data.getlist("pm_f4_events") or self.initial.get("pm_f4_events")
        if selected_F4Events:
            # check of selected values not object
            if not isinstance(selected_F4Events[0], F4Events):
                selected_F4Events = pm_f4_events_field.queryset.filter(pk__in=selected_F4Events)
            choices_F4Events = [(item.pk, item.name) for item in selected_F4Events]
        # assign selected values or empty list
        pm_f4_events_field.choices = choices_F4Events

Has been tested on my server, works well.

👤NKSM

Leave a comment