ModelForm 和 ModelSelect2Widget (django-select2)

ModelForm and ModelSelect2Widget (django-select2)

我有一个 ModelForm,其中包含来自 django-select2 的 ModelSelect2Widget

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

按照此处的文档:

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 包含大约 100 个条目。

在我看来,一切看起来都很好,但在呈现的模板中,name 下拉列表中没有可用数据。

控制台登录 Google Chrome 显示:

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

您是否遵循了 getting started section 中的所有步骤?

  1. Add django_select2 to your INSTALLED_APPS in your project settings.

  2. Add django_select to your urlconf if you use any ModelWidgets:

    url(r'^select2/', include('django_select2.urls')),
    
  3. Add the CSS to the head of your Django template:

    {{ form.media.css }} 
    
  4. Add the JavaScript to the end of the body of your Django template:

    {{ form.media.js }}
    

此外,模块本身似乎没有提供外部依赖项:

External Dependencies

jQuery version 2 This is not included in the package since it is expected that in most scenarios this would already be available.

找到解决方案:

{{ form.media.js }}

需要在导入jquery之后。

好吧,我最近也遇到过这种情况...结果是 jquery 脚本

(<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>)

应该放在任何使用 jquery 的脚本之前(它将使用 jquery,但尚未调用 jquery)。