这个问题已经问了很多遍了。我经历了很多,但仍然找不到我想要的东西。
我正在尝试仅在Django-Admin中的父ModelChoiceField选择上加载子ModelChoiceField数据
我的代码如下:
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)
但不适用于
onChange
事件。 最佳答案
这是我为汽车准备的。您可以通过将Car Make替换为国家/地区并将Car Model替换为城市来进行调整
在__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视图
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网址
path('ajax/load-models/', views.load_models, name="ajax_load_models"),
模板中的Javascript(使用JQuery)
$("#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
}
});
});
关于python - Django Admin-父ModelChoiceField上的动态子ModelChoiceField查询集,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56449395/