I would like to render two selects with Django (one multiple select, the other a simple one) and customize it with Materialize. I managed to code the following:
In my forms.py
class ZonesForm(forms.Form):
zones_options = (
(1, 'Zone 1'),
(2, 'Zone 2'),
(3, 'Zone 3'),
(4, 'Zone 4')
)
zones = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=zones_options)
conn_options = (
(1, 'ABCDE'),
(2, 'FGHIJ'),
)
connections = forms.ChoiceField(choices=conn_options)
In my zones.html
{% block content %}
<div class="container">
<div class="row">
<form method="post">
<div class="input-field col s6">
<select multiple name="{{ form.zones.name }}">
{% for opt in form.zones %}
<option value="{{ opt.id }}">{{ opt.label }}</option>
{% endfor %}
</select>
<label>Zones</label>
</div>
<div class="input-field col s6">
<select name="form.connections.name">
{% for opt in form.connections %}
<option value="{{ opt.id }}">{{ opt }}</option>
{% endfor %}
</select>
<label>Connection</label>
</div>
</form>
</div>
</div>
{% endblock %}
My problem is: when the page is rendered, I get 4 checkboxes for the first select (as expected), and no names for it (all options are blank). For the second select I get 4 options (one blank, one with 'ABCDE', one blank, one with 'FGHIJ').
I suspect that the problem is with the attributes. I am not getting the right values for them (I have tried opt.label, opt.text, opt.choices, opt.value, opt...). How can I access them correctly?
Another question: is there a nice way to debug through it? I am new to Django and to web-dev in general. I tried import pdb; pdb.set_trace() to debug through it but I could not get pass my break point to navigate through other methods (I am using PyCharm).
I managed to fix the problem and I am posting this answer in case someone faces a similar issue.
For the first select, in forms.py I replaced widget=forms.CheckboxSelectMultiple
with widget=forms.SelectMultiple
. Surprisingly enough, the checkboxes are rendered correctly. I am not sure about the difference between CheckboxSelectMultiple
and SelectMultiple
but the later works =)
For both cases I had to change my zones.html. It looks like this now:
{% block content %}
<div class="container">
<div class="row">
<form method="post">
<div class="input-field col s6">
{{ form.zones }}
<label>Zones</label>
</div>
<div class="input-field col s6">
{{ form.connections }}
<label>Connection</label>
</div>
</form>
</div>
</div>
{% endblock %}