djangodjango-formsjquery-select2django-select2

Select2MultipleWidget in formset is not rendering


I'm trying to get a formset with Select2MultipleWidget widgets but am not successful. Using Django 2.2 LTS.

My (simplified) model goes below:

class Meal(models.Model):

    noon = models.BooleanField("Meal noon", default=False)
    noon_options = models.ManyToManyField(MealOption, related_name='real_noon_options', blank=True)
    evening = models.BooleanField("Meal evening", default=False)
    comments = models.TextField("Comments", blank=True, null=True)

The form I'm using goes as follows:

class MealUpdateForm(forms.ModelForm):

    class Meta:
        model = Meal
        fields = ('noon', 'noon_options', 'evening', 'comments', )
        widgets = {
            'noon_options': Select2MultipleWidget,
        }

When I render the above through a test form for a single item, everything is working fine: I get a Select2MultipleWidget for the noon_options field.

Whenever I add the form to a modelformset_factory though, I'm getting Django's default SelectMultiple widget, which is not what I want.

MealFormSet = modelformset_factory(Meal, 
                                   extra=0, 
                                   fields=('noon', 'noon_options', 'evening', 'comments', ),
                                   form=MealUpdateForm, )

I'm rendering the formset in my template pretty straightforward as:

{% for form in formset.forms %}
    <tr>
        <td>
            {{ form.id }}
        </td>
        <td>
            {{ form.noon }}
        </td>
        <td>
            {{ form.noon_options }}
        </td>
        <td>
            {{ form.evening }}
        </td>
        <td>
            {{ form.comments }}
        </td>
    </tr>
{% endfor %}

Any idea what I'm doing wrong?

Per this question/answer, I tried adding widgets={'noon_options': Select2MultipleWidget} to the modelformset_factory definition, this doesn't help: I'm still stuck with the original SelectMultiple widget.


Solution

  • When manually rendering the form, you must load the JS and CSS files manually as well:

    {# Required to render the Select2 widgets #}
    {{ formset.media.js }}
    {{ formset.media.css }}
    
    {% for form in formset.forms %}
    ...