Search code examples
pythondjangodjango-formsdjango-select2

ModelForm and ModelSelect2Widget (django-select2)


I have a ModelForm which includes a ModelSelect2Widget from django-select2

https://github.com/applegrew/django-select2

Following the Documentation from here:

https://django-select2.readthedocs.io/en/latest/django_select2.html#django_select2.forms.ModelSelect2Widget

forms.py

class RentalForm(forms.ModelForm):


    name = forms.ChoiceField(
            widget=ModelSelect2Widget(
                model=ldap_data,
                search_fields=['user__icontains']
            )
        )
    date_start = forms.CharField(label="Datum Ausleihe", help_text="", widget=forms.TextInput(attrs={'class': 'form-control form-control-sm', 'placeholder': '01.01.2019' }))
    date_end = forms.CharField(label="Datum Rückgabe", help_text="", widget=forms.TextInput(attrs={'class': 'form-control form-control-sm', 'placeholder': '01.01.2019' }))

    class Meta:
        model = Rental
        fields = ['device', 'name', 'date_start', 'date_end',]

models.py

class ldap_data(models.Model):
    user = models.CharField(max_length=1024)

    def __str__(self):
        return self.user

ldap_data contains around 100 entries.

In my opinion everything looks fine, but in the rendered template no data is available in the name dropdown.

Console Log in Google Chrome shows:

select2.min.js:1 Uncaught ReferenceError: jQuery is not defined
    at select2.min.js:1
    at select2.min.js:1
(anonymous) @ select2.min.js:1
(anonymous) @ select2.min.js:1
django_select2.js:9 Uncaught ReferenceError: jQuery is not defined
    at django_select2.js:9
    at django_select2.js:11

Solution

  • Found the solution:

    {{ form.media.js }}

    needs to be after the import of jquery.