如何调试 django-select2 下拉菜单

How to debug django-select2 dropdown

我喜欢根据模型的下拉选项创建一个文本搜索字段。我选择了 django-select2 但它不起作用。 这是输出 HTML

 <form class="add_new container" method="post">
    <h3 class="text-center">Issue Book</h3><hr><br>
    {% csrf_token %}
    <h4> Choose the student to issue book to</h4><br>
    {% for field in form %}
        {{ field }}
    {% endfor %}<hr><br>
    <input type="submit" value="Issue" class="btn btn-dark text-right" style="float:right">
  </form>

这是表格

class NewIssueForm(forms.ModelForm):
    def __init__(self,*args, pk,school,issuer, **kwargs):
        super(NewIssueForm, self).__init__(*args, **kwargs)
        self.fields['issuer'].initial = issuer
        self.fields['borrower_id'].queryset = Student.objects.filter(school=school)
        self.fields['book_id'].initial = pk #Sets the field with the pk and it's hidden again
    class Meta:
        model = Issue
        fields = ['issuer','book_id','borrower_id']
        widgets = { }
        widgets = {
            'book_id':forms.TextInput(attrs={"class":'form-control','type':'hidden'}),
            'issuer':forms.TextInput(attrs={"class":'form-control','type':'hidden'}),
            'borrower_id': Select2Widget,
        }

Settings.py 如下

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    'select2': {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/2",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

需要设置多个部分才能使 django-select2 正常工作:

  1. jQuery 需要包含在您的模板中。它不包含在 django-select2 中,因此您需要提供自己的。如果缺少此项,您将在浏览器的开发人员工具中收到错误消息。
  2. 表单媒体需要包含在页面上。如果 header 中没有 {{ form.media.css }},您将不会获得任何自定义样式,如果某处没有 {{ form.media.js }}(例如 <body> 的底部),您将获胜'获得任何自定义行为。
  3. django_select2.urls 需要包含在您的 URL 配置中。没有它,当 select2 试图解析 URLs 时,你可能会得到一个错误,所以你可能做对了。

另见 the official documentation of django-select2