Show and hide dynamically fields in Django form

2019-06-21 20:02发布

I have a form in Django:

views.py:

class SearchForm(forms.Form):
    type = forms.ChoiceField(choices = ...)
    list1 = forms.ModelMultipleChoiceField(...)
    list2 = forms.ModelMultipleChoiceField(...)

home.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>

I want the list1 element to be shown and the list2 to be hide if type is 1 and vice versa in case type is 2. I want them to be hide and shown dynamically without reloading the page or any interaction with the server.

I believe Javascript could be useful here, but I don't know it.

2条回答
乱世女痞
2楼-- · 2019-06-21 20:43

This is an adaption of Andrew's Javascript solution, using Django forms the way you'd usually expect.

The form in 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()

The template, assuming an instance of SearchForm got passed to the template context with the name '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>
查看更多
仙女界的扛把子
3楼-- · 2019-06-21 20:50

Try this...

<script>function Hide()
{
    if(document.getElementById('mainselect').options[document.getElementById('mainselect').selectedIndex].value == "1")
    {
         document.getElementById('a').style.display = 'none';
         document.getElementById('b').style.display = '';
    }else
    {
         document.getElementById('a').style.display = '';
         document.getElementById('b').style.display = 'none'
    }
}
</script>
<td valign='top'><select id="mainselect" onchange="Hide()"><option value="1">1</option><option value="2">2</option></select></td>
<td valign='top' id='a'>{{ form.list1 }}</td>
<td valign='top' id='b'>{{ form.list2 }}</td>
<td valign='top'><input type="submit" value="Find" /></td>
查看更多
登录 后发表回答