Reputation: 291
I'm trying to setting up a select
control on a form, but not achieving the expected results. For me, the strangest thing is it working in the previous control, same type.
This is the function involved:
class ProofMSPE(CrearEvidencia):
model = VRL02
form_class = VRL02Form
def get_form(self, form_class):
form = super(ProofMSPE, self).get_form(form_class)
form.fields['miembro'].queryset = self.pipol
if self.pipol.count() == 1:
form.fields['miembro'].widget.initial = [self.pipol[0].id]
form.fields['meta'].initial = self.meta
form.fields['meta'].widget.attrs['disabled'] = True
return form
The meta
's control is select
and I got the expected behavior, ie automatically selects an initial value (form.fields['meta'].initial = self.meta
and inthe next lines, it disabled (form.fields ['meta']. widget.attrs ['disabled'] = True
). This is the output in the rendered template:
<!-- begin meta-->
<div class="row">
<div class="col s12 input-field">
<select id="id_meta" name="meta" disabled>
<option value="">---------</option>
<option value="1" selected="selected">JOCE-1</option>
<option value="2">VEL-1</option>
<option value="3">VEL-2</option>
<option value="4">VEL-3</option>
</select>
<label for="id_meta">Evidencia para la meta</label>
</div>
</div>
<!-- end ./meta -->
On the other hand, with the pipol
field I'm unable to get the same result. The difference, by the way, is this field has some logic: I get a filtered list of people with same criteria and the widget is create whit this list (form.fields['miembro'].queryset = self.pipol
).
So far so good, but if the queryset has only one result (if self.pipol.count () == 1 :
) I want that this one to be used as inital value (form.fields ['member']. Widget.initial = [self .pipol [0] .id]
), but this is not working.
This is what appears when the template is rendered:
<!-- begin pipol-->
<div class="row">
<div class="col s12 input-field">
<select id="id_miembro" name="miembro">
<option value="" selected="selected">---------</option>
<option value="2">***@***.mx</option>
</select>
<label for="id_miembro">Seleccione el usuario</label>
</div>
</div>
<!-- end ./pipol -->
Thanks for your time.
Upvotes: 3
Views: 2252
Reputation: 2136
You have to set the initial value to the form.field['miembro']
and not the widget, like you did with form.fields['meta']
.
def get_form(self, form_class):
form = super(ProofMSPE, self).get_form(form_class)
form.fields['miembro'].queryset = self.pipol
if self.pipol.count() == 1:
# this line here
form.fields['miembro'].initial = self.pipol[0]
form.fields['meta'].initial = self.meta
form.fields['meta'].widget.attrs['disabled'] = True
return form
Select output would be:
<select id="id_miembro" name="miembro">
<option value="">---------</option>
<option value="2" selected="selected">***@***.mx</option>
</select>
Upvotes: 3