I have a task to create a dynamic web form that includes select fields whose options depend on the selections made in previous fields. An example of this would be a form for selecting vehicle year > make > model, where the available choices for 'make' only appear after a 'year' is selected and the choices for 'model' are based on both the selected 'year' and 'make'. The SQL queries to populate each field would follow this pattern:
select distinct year from cars
select distinct make from cars where year = [selected year]
select distinct model from cars where year = [selected year] and make = [selected make]
This feature needs to be implemented within an existing Django project. Although I am new to creating such forms, I do understand the basics of using asynchronous JavaScript calls to support them.
The structure of the form should resemble the following:
class CarForm(forms.Form):
year = forms.ChoiceField(choices=get_years())
make = forms.ChoiceField(choices=get_makes(year))
model = forms.ChoiceField(choices=get_models(year, make))
The corresponding view code looks like:
def save_car(request):
if request.method == 'POST':
form = CarForm(request.POST)
if form.is_valid():
handle_results(form.cleaned_data)
return HttpResponse('Success')
else:
form = CarForm()
return render_to_response('car.html', locals())
My main question revolves around updating the choices available for each select field dynamically. I would appreciate any guidance on this matter!