简体   繁体   English

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

[英]Django Admin- Dynamic child ModelChoiceField queryset on parent ModelChoiceField

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 我正在尝试仅在Django-Admin中的父ModelChoiceField选择上加载子ModelChoiceField数据

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. 但不适用于onChange事件。

Here's one I did for cars. 这是我为汽车做的。 You can adapt it by replacing Car Make with country and Car Model with city 您可以通过将Car Make替换为国家/地区并将Car Model替换为城市来适应

Within the form __init__ 形式为__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 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 url Ajax网址

path('ajax/load-models/', views.load_models, name="ajax_load_models"),

Javascript (using JQuery) in template 模板中的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
        }
    });

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM