Want can Ajax work with a dynamic Django dropdown list? I would go for a REST service, like Django Rest Framework, and then use jquery to autopopulate the dropdowns.
If installing a REST service is a hassle, you could write a couple of views to get the data in json format. For instance, if you have a REST service in /myapp/api, you could populate the Cars like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $.ajax({ url: "/myapp/api/cars?format=json", dataType: "json", success: function( data ) { var makes=[]; for (var i in data) { car = data[i]; if (makes.indexOf(car.make) < 0){ // avoid duplicate brands makes.push(car.make); $('#makeselect').append($('<option>', { value: car.id, text: car.make })); } } } }); |
Then, attach a handler when the “make” selector has changed, and populate the model and year accordingly using another REST call, like /myapp/api/cars?make=Ford.
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.