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.2 Django 4.2 Django 3.2 django-autocomplete-light

Django/Python Consulting

If you have a specific Django challenge or integration you'd like to solve, I'd be happy to help. Book a free 30-minute call to discuss your project, see if we're a good fit, and explore the best approach for your needs. After the call, you'll receive a tailored cost estimate based on what we discuss.