This question have been asked many times. I went through many of them, and still couldn't find what i am looking for.
I am trying to load child ModelChoiceField data on parent ModelChoiceField selection in Django-Admin only
My code is as follows:
class AddressForm(forms.ModelForm):
name = forms.CharField(max_length=150)
city = forms.ModelChoiceField(queryset=City.objects.all(), required=False)
class Meta:
model = Address
fields = ['name', 'country', 'city']
def __init__(self, *args, **kwargs):
if 'instance' in kwargs:
address = kwargs['instance']
self.base_fields['name'].initial = address.name
country = self.get_country(*args, **kwargs)
self.base_fields['city'].queryset = country.cities if country else City.objects.none()
super().__init__(*args, **kwargs)
but it's not working on onChange
event.
Here's one I did for cars. You can adapt it by replacing Car Make with country and Car Model with city
Within the form __init__
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['car_make'].empty_label = 'Make'
self.fields['car_model'].empty_label = 'Model'
initial = kwargs.get('initial', None)
try: self.fields['car_model'].queryset = CarModel.objects.filter(car_make=initial['car_make'])
except: self.fields['car_model'].queryset = CarModel.objects.none()
Ajax view
def load_models(request):
car_make_id = request.GET.get('car_make')
car_models = CarModel.objects.filter(car_make_id=car_make_id).order_by('name')
return render(request, 'leases/partials/car_model_dropdown_list_options.html', {'car_models': car_models})
Ajax url
path('ajax/load-models/', views.load_models, name="ajax_load_models"),
Javascript (using JQuery) in template
$("#id_car_make").change(function () {
var url = $("#searchForm").attr("data-models-url"); // get the url of the `load_cities` view
var carMakeId = $(this).val(); // get the selected country ID from the HTML input
$.ajax({ // initialize an AJAX request
url: url, // set the url of the request (= localhost:8000/hr/ajax/load-cities/)
data: {
'car_make': carMakeId // add the country id to the GET parameters
},
success: function (data) { // `data` is the return of the `load_cities` view function
$("#id_car_model").html(data); // replace the contents of the city input with the data that came from the server
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.