I have installed django-autocomplete-light
.
My form without autocomplete looks like this:
class FilterForm(forms.Form):
form_origin = forms.CharField(label='From country',
max_length=100,
required=False,
widget=forms.TextInput(attrs={
'placeholder': 'From country',
'arial-label':'C2',
}))
form_target = forms.CharField(label='To country',
max_length=100,
required=False,
widget=forms.TextInput(attrs={
'placeholder': 'To country',
'arial-label': 'C1',
}))
I have written a view following the instructions here, which gives all the countries which start with the same letter as my input.
class CountryAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = Country.objects.all()
qs = qs.filter(name__istartswith=self.q)
return qs
However, I am having issues with using it with the form, which has two char fields, both to use the same model called Country
. The tutorial isn't tailored to that. In essence, I hope to have two text boxes, with autocomplete of the country to and from, a bit like skyscanner. Any advice to the right direction is appreciated!
My model looks like this:
class Country(models.Model):
iso3 = models.CharField('3 Digit ISO', max_length=3, unique=True)
name = models.CharField('Name', max_length=50)
lon = models.FloatField()
lat = models.FloatField()
def __str__(self):
return self.name
UPDATE:
My url is this:
re_path(r'^country-autocomplete/$', views.CountryAutocomplete.as_view(), name='country-autocomplete'),
I've updated my form to this, following help from Sumit:
form_origin = forms.CharField(label='From country',
max_length=100,
required=False,
widget=autocomplete.ListSelect2(
url='myapp:country-autocomplete',
))
However I get a dropdown where there are no selectable fields:
I am using bootstrap and my template looks like this:
{% for field in form %}
<div class="form-inline form-group">
<div class="col-sm-10">
{{ field|attr:"class:form-control" }}
</div>
</div>
{% endfor %}