About Dependent Autocompletes
You can create one autocomplete field dependent on another one with django-autocomplete-light
pretty easy using the special forwarding feature:
# shops/forms.py
from django import forms
from dal import autocomplete
from .models import Country, City
class ShopLocationForm(forms.Form):
country = forms.ModelChoiceField(
queryset=Country.objects.all(),
widget=autocomplete.ModelSelect2(
url="country-autocomplete",
)
)
city = forms.ModelChoiceField(
queryset=City.objects.all(),
widget=autocomplete.ModelSelect2(
url="city-autocomplete",
forward=["country"],
)
)
Then you would define your views that return autocompleted values as follows:
# shops/views.py
from dal import autocomplete
from .models import Country, City
class CountryAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = Country.objects.all()
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
class CityAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = City.objects.all()
country = self.forwarded.get("country", None)
if country:
qs = qs.filter(country=country)
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
The JavaScript of django-autocomplete-light
connects the fields in the frontend, and moreover, it is smart enough to work with prefixed and inline forms.
Tips and Tricks Programming Development Django 5.x Django 4.2 Django 3.2 django-autocomplete-light
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.