我在 Django 中有一个表单:
views.py:
class SearchForm(forms.Form):
type = forms.ChoiceField(choices = ...)
list1 = forms.ModelMultipleChoiceField(...)
list2 = forms.ModelMultipleChoiceField(...)
主页.htm:
<td valign='top'>{{ form.type }}</td>
<td valign='top'>{{ form.list1 }}</td>
<td valign='top'>{{ form.list2 }}</td>
<td valign='top'><input type="submit" value="Find" /></td>
如果类型为 1,我希望显示 list1 元素,如果类型为 2,则隐藏 list2 元素,反之亦然。我希望它们动态隐藏和显示,而无需重新加载页面或与服务器进行任何交互。
我相信 Javascript 在这里很有用,但我不知道。
最佳答案
这是对 Andrew 的 Javascript 解决方案的改编,按照您通常期望的方式使用 Django 表单。
Django/Python 中的表单:
class SearchForm(forms.Form):
type = forms.ChoiceField(choices = ((1, 'One'), (2, 'Two')))
# Use any form fields you need, CharField for simplicity reasons
list1 = forms.CharField()
list2 = forms.CharField()
模板,假设 SearchForm
的一个实例被传递给名为“form”的模板上下文:
<script>
function Hide() {
if(document.getElementById('id_type').options[document.getElementById('id_type').selectedIndex].value == "1") {
document.getElementById('id_list1').style.display = 'none';
document.getElementById('id_list2').style.display = '';
} else {
document.getElementById('id_list1').style.display = '';
document.getElementById('id_list2').style.display = 'none';
}
}
window.onload = function() {
document.getElementById('id_type').onchange = Hide;
};
</script>
<div>
{{ form.type.label_tag }}{{ form.type }}
</div>
<div>
{{ form.list1.label_tag }}{{ form.list1 }}
</div>
<div>
{{ form.list2.label_tag }}{{ form.list2 }}
</div>
关于javascript - 在 Django 表单中动态显示和隐藏字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15136657/