簡體   English   中英

Django Admin-父ModelChoiceField上的動態子ModelChoiceField查詢集

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

這個問題已經問了很多遍了。 我經歷了很多,但仍然找不到我想要的東西。

我正在嘗試僅在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
        }
    });

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM