gpt4 book ai didi

python - django 中的类别-子类别下拉列表

转载 作者:行者123 更新时间:2023-11-28 18:47:00 24 4
gpt4 key购买 nike

我需要根据已显示的类别类型显示子类别。像这样的东西

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 %}

最佳答案

这是一种使用 jQuery 的有点老套的方法,我相信有更好的方法,但它可能会给您一些想法。我不确定您在寻找什么,因此它与您的型号不完全匹配。类型可能是您的类别字段,然后我用子类别填充类别字段。 Subcats 可以是两个列表之一,具体取决于 Type 的设置。

在模板中显示表单域:

  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>

关于python - django 中的类别-子类别下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18574529/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com