Django Admin-父ModelChoiceField上的动态子ModelChoiceField查询集

时间:2019-06-04 18:24:18

标签: python django django-forms django-admin

this question have been asked many times. i went through many of them. still couldn't find what i am looking for.

我正在尝试仅在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事件。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

这是我为汽车所做的。您可以通过将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
        }
    });

});