我有一个包含两个字段的表单,这两个字段基于两个模型。我需要的?如果选择特定类别,则只能选择与特定类别绑定的子类别。
表单
category = forms.ModelChoiceField(
label='Category',
queryset=Category.objects.all(),
widget=forms.Select,
required=False)
subcategory = forms.ModelChoiceField(
label='Subcategory',
queryset=SubCategory.objects.all(), #may be something like SubCategory.objects.filter(??????)
widget=forms.Select,
required=False)
答案 0 :(得分:1)
Ajax / jQuery解决方案:
<script type='text/javascript'>
$(function(){
$('select[name=subcategory]').empty();
$('select[name=subcategory]').prepend('<option value="Not selected" selected disabled>Select Category...</option>');
// called when category field changes from initial value
$('select[name=massage]').change(function(){
if($("#id_category option:selected").text()) != (YOU SHOULD INSERT THE INITIAL VALUE OF THE CATEGORY FIELD WHEN IT IS NOT SELECTED) {
category_id = $('select[name=category]').val();
request_url = '/get_subcategory/' + category_id + '/';
$.ajax({
url: request_url,
type: "GET",
success: function(data){
$.each(data, function(key, value){
$('select[name=subcategory]').empty();
$('select[name=subcategory]').append('<option value="' + key + '">' + value + '</option>');
});
}
})
}
})
});
</script>
:
url(r'^get_subcategory/(?P<category_id>[0-9]+)/$', views.get_subcategory, name='get_subcategory'),
:
import json
def get_subcategory(request, category_id):
category = Category.objects.get(pk=category_id)
subcategories = category.subcategory_set.all()
subcategories_dict = {}
for subcategory in subcategories:
// if your subcategory has field name
subcategories_dict[subcategory.id] = subcategory.name
return HttpResponse(json.dumps(subcategories_dict), content_type="application/json")