Reputation: 4547
I need to show a sub-Category depending on the type of category that has been shown. Some thing like this
Group 1
==>Group1_subcat1
==>Group1_subcat2
Group 2
==>Group2_subcat1
==>Group2_subcat2
Models
class Category(models.Model):
category=models.CharField(max_length=20)
description=models.CharField(max_length=64)
group=models.ForeignKey(Group)
Forms
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 %}
Upvotes: 3
Views: 1995
Reputation: 8570
This is a somewhat hacky approach using jQuery, I'm sure there is a better way but it might give you some ideas. I'm not sure exactly what you are looking for so it does not match your model exactly. Type might be your Category field and then I'm populating the Category field with subcategories. Subcats can be one of two lists depending on the setting of Type.
In the template display the form field:
Type {{form.org_type}}
Category {{form.category}}
Then added some javascript to the template:
<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>
Upvotes: 1