我需要根据已显示的类别类型显示子类别。 像这样的事情
Group 1
==>Group1_subcat1
==>Group1_subcat2
Group 2
==>Group2_subcat1
==>Group2_subcat2
模型
class Category(models.Model):
category=models.CharField(max_length=20)
description=models.CharField(max_length=64)
group=models.ForeignKey(Group)
表单
class ContactForm(forms.Form):
'''Creates a form for the application to add a contact. '''
firstname = forms.CharField(max_length=20)
lastname = forms.CharField(max_length=20)
email = forms.EmailField()
group = forms.ModelChoiceField(queryset=Group.objects.all())
category=forms.ModelChoiceField(queryset=Category.objects.filter(group=group.id))//error is here
HTML
{% csrf_token %}
{{ form.as_p }}
{% endfor %}
答案 0 :(得分:1)
这是一种使用jQuery的有点hacky方法,我确信有更好的方法,但它可能会给你一些想法。我不确定你到底在找什么,所以它与你的模型完全不符。类型可能是您的类别字段,然后我填充子类别的类别字段。根据Type的设置,Subcats可以是两个列表中的一个。
在模板中显示表单字段:
Type {{form.org_type}}
Category {{form.category}}
然后在模板中添加了一些javascript:
<script type="text/javascript">
$(document).ready(function() {
// subcatlist1 and subcatlist2 are querysets passed to the template.
var subcat_1 = ' {% for subcat in subcatlist1 %}<option value="{{subcat.id}}">{{subcat.name}}</option> {% endfor %}';
var subcat_2 = ' {% for subcat in subcatlist2 %}<option value="{{subcat.id}}">{{subcat.name}}</option> {% endfor %}';
// initialise subcat choices based on type
subcat_choices();
// if the type field is changed, change the subcategory list
$('#id_org_type').change(function() {
subcat_choices();
});
function subcat_choices() {
// change the content of the category dropdown to hold a list of subcategories
if ($("#id_org_type option:selected").val() == '1') {
$("#id_category").html(subcat_1);
} else {
$("#id_category").html(subcat_2);
}
}
});
</script>