我喜欢创建一个基于模型下拉选项的文本搜索字段。我选择了django-select2 2,但它不起作用。这是输出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",
}
}
}发布于 2021-05-29 09:40:31
为了使django-select2工作,需要设置多个部分:
django-select2中,所以您需要提供自己的。如果缺少这一点,您将在浏览器的开发工具中得到一个错误。{{ form.media.css }},就不会得到任何定制样式,如果没有{{ form.media.js }} (例如,在<body>的底部),您就不会得到任何定制行为。django_select2.urls需要包含在您的URL中。如果没有它,当select2试图解析URL时,您可能会得到一个错误,所以您可能正确地理解了这个错误。https://stackoverflow.com/questions/67749726
复制相似问题