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

标签 python django django-forms django-admin

这个问题已经被问过很多次了。我浏览了很多,但仍然找不到我要找的东西。

我正在尝试仅在 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 事件。

最佳答案

这是我为汽车做的一个。您可以通过将汽车制造替换为国家/地区并将汽车型号替换为城市来进行调整

__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 网址

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/

相关文章:

python - 对于这种情况,Python 和 Hadoop 的选择是否合适?

python - 泡菜 : TypeError: a bytes-like object is required, 不是 'str'

python - 类型 'HttpResponse' 的对象的 Django 分页错误没有 len()

python - 设置不属于模型表单一部分的模型字段的值

python - 在python中添加分隔符

python - Pandas :如何在同一单元格上读取多行 csv?

django - 对于大量选择,ModelChoiceField有哪些替代方案?

python - Django rest 框架中的 self.get_serializer 和 Serializer 对象有什么区别?

django - 如何在 Django 表单中将标签设置为粗体?

django - 如何在Django表单中显示下标字母?