我讀過http://django-autocomplete-light.readthedocs.io/en/master/tutorial.html#using-autocompletes-outside-the-admin使用Django的自動完成光外管理視圖
,並試圖用一個簡單的HTML頁面內的小部件,但它不工作,沒有的JavaScript和Python的錯誤。 這裏是我的代碼:
# models.py
class Doctor(models.Model):
name = models.CharField(max_length=200)
address = models.CharField(max_length=200, null=True, blank=True, default='')
def __unicode__(self):
return self.name
class Patient(models.Model):
name = models.CharField(max_length=200)
sample = models.OneToOneField(Sample, null=True, blank=True)
doctor = models.ForeignKey(Doctor, null=True, blank=True, default=None)
def __unicode__(self):
return self.name
# views.py
class DoctorAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated():
return Doctor.objects.none()
qs = Doctor.objects.all()
if self.q:
qs = qs.filter(name__icontains=self.q)
return qs
class DocForm(autocomplete.FutureModelForm):
class Meta:
model = Doctor
fields = ('name',)
widgets = {
'doctor': autocomplete.ModelSelect2(url='doc-autocomplete'),
}
class Index(generic.UpdateView):
model = Doctor
form_class = DocForm
template_name = 'index.html'
success_url = reverse_lazy('index')
def get_object(self):
return Doctor.objects.first()
# index.html
<html>
<head>
<script type="text/javascript" src="/static/admin/js/jquery.js"></script>
</head>
<body>
Welcome
<div>
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" />
</form>
</div>
</body>
</html>
我只想用自己的不錯選擇2小部件列出與醫生IDS醫生的名字,如自動完成值。我可以在沒有django-autocomplete-light的情況下做到這一點,但我明確地想要學習如何使用看起來更好的widget。 有人能指導我讓它工作嗎?
我很高興你解決了它。我會在我的答覆的相關部分糾正疏忽,謝謝! – raratiru