Check
https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html
Also, I recently had a similar task with companies and divisions
from querysets and had trouble using the form.__init__() method.
Here is an alternative approach. You can tweak what the form
displays by calling a form method - here set_division_queryset(). In
other words, you can populate selection choices based on code
elsewhere. In my case I did it from within the view code like this
...
# forms.py
class List_Import(forms.Form):
...
division = forms.ModelChoiceField(
required=False,
empty_label="Must select a Division",
queryset=Division.objects.none(),
...
def set_division_queryset(self, divqs):
self.fields["division"].queryset = divqs
def clean(self):
cleaned_data = super().clean()
selected_division = cleaned_data.get('division')
available_divisions = self.fields['division'].queryset
if selected_division not in available_divisions:
self.add_error('division', 'Invalid choice. Please select a valid division.')
return cleaned_data
# views.py
@login_required(redirect_field_name="next")
@ensure_csrf_cookie
def list_import(request, template="list_import.html", context=None):
...
# User model has get_company() method and Company has get_all_divisions()
divqs = request.user.get_company().get_all_divisions()
form.set_division_queryset(divqs)
...
if request.method == 'POST':
form = List_Import(request.POST, request.FILES)
# because form.is_valid() needs available_divisions and we are
# not using form.__init__(), we have to send divqs again
form.set_division_queryset(divqs)
if form.is_valid():
...
Cheers
Mike