我在django 1.8中使用django-autocomplete-light
。但我不知道如何在forms.py
中使用它。而不是自动完成字段,我看到一个选择字段。我按照here的说明进行操作。
在models.py
我有:
class icd_10(models.Model):
id = models.IntegerField(unique=True,primary_key=True,null=False,blank=False)
icd_10_desc = models.CharField('ICD-10 description',max_length=80,null=True,blank=True)
icd_10_code = models.CharField('ICD-10 code',max_length=10,null=True,blank=True)
def __str__(self):
return str(self.icd_10_desc)
class Diagnosis(models.Model):
diagnosis_option = models.ManyToManyField(DiagnosisOption)
record_of_genotype = models.CharField(max_length=45,null=True,blank=True)
icd_10_desc = models.ManyToManyField(icd_10)
patient = models.ForeignKey(Demographic)
def __str__(self):
return str(self.patient)
在settings.py
我有:
INSTALLED_APPS = (
'dal',
'dal_select2',
'django.contrib.admin',
...
)
在views.py
我有:
class IcdTenAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
#Don't forget to filter out results depending on the visitor !
if not self.request.user.is_authenticated():
return icd_10.objects.none()
qs = icd_10.objects.all()
if self.q:
qs = qs.filter(icd_10_desc__istartswith=self.q)
return qs
在urls.py
我有:
url(r'^icd10-autocomplete/$','eReg.views.IcdTenAutocomplete',name='icd10-autocomplete'),
在forms.py
我有:
class DiagnosisForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(DiagnosisForm, self).__init__(*args, **kwargs)
self.helper.layout = Layout(
Fieldset (
# 'patient',
'<b>Diagnosis information</b>',
'diagnosis_option',
'icd_10_desc',
),
FormActions(
Submit('submit', "Save changes"),
Submit('cancel',"Cancel")
),
)
self.helper.form_tag = False
self.helper.form_show_labels = True
class Meta:
model = Diagnosis
exclude = ['patient', 'author']
list_display = ('patient', 'pub_date', 'author')
widgets={'icd10_desc' : autocomplete.ModelSelect2Multiple(url='icd10-autocomplete')}
当我直接从浏览器运行它时,它可以正常工作。我得到了
{"pagination": {"more": false}, "results": [{"text": "Thalassemia", "id": 8}, {"text": "Thalassemia trait", "id": 12}, {"text": "Thalassemia, unspecified", "id": 15}]}
那么,我错过了一个合适的JavaScript吗?
答案 0 :(得分:1)
我找到了解决方案!我必须在我的模板中包含以下代码:
{% block footer %}
<script type="text/javascript" src="http://dal-yourlabs.rhcloud.com/static/collected/admin/js/vendor/jquery/jquery.js"></script>
{{ frm.media }}
{% endblock %}
以下代码在我的模板继承数据的base.html中。
<link src="/static/collected/autocomplete_light/vendor/select2/dist/css/select2.css" type="text/css" media="all" rel="stylesheet" />
<link src="/static/collected/autocomplete_light/select2.css" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/static/collected/autocomplete_light/autocomplete.init.js"></script>
<script type="text/javascript" src="/static/collected/autocomplete_light/select2.js"></script>