Przemek
Przemek

Reputation: 459

Get Value Of Selected Option ModelChoiceField

Without using Ajax is there a way to get the value of a selected item. So for example, if I have the below drop down list:

<select name="controllers" id="id_controllers">
<option value="" selected="selected">---------</option>
<option value="1">http://przemeklach.com/api/firstOrder/przemeksController</option>
<option value="5">http://przemeklach.com/api/zeroOrder/ronsController</option>
</select>

How would I get at the 'value' in my view. I know I can get the 'http://przemeklach.com/api/firstOrder/przemeksController' part via

controller = form.cleaned_data['controllers']

but I also need the 'value' in this case 1.

Thanks.

Upvotes: 1

Views: 4260

Answers (1)

Makdaam
Makdaam

Reputation: 51

Scratch the old response (below), cleaned_data contains object references. You can get the ID by refering to model methods.

You can get the id from form.data['controllers'] but it needs sanity checking (in this case it should be an int). Of course if the is_valid() returns True it should be one of the ids available in the queryset you supplied when defining the field.

Upvotes: 1

Related Questions