ChemseddineZ
ChemseddineZ

Reputation: 1818

sending multiple values from django dropdown

I have a django form with a dropdown menu

<form action="/dir/" method="POST">{% csrf_token %}
    <table>
      <tr><td>
        <select name="listxblocks">
          {% for scname, desc in scenarios %}
          <!--<option value="{% url "workbench_show_scenario" scname %}">{{desc}}/{{scname}}</option>-->
          <option value="{{scname}}">{{desc}}/{{scname}}</option>

          {% endfor %}

        </select>

        </td>
    <td></td></tr>
    </table>
    <input type="submit" value="Save"/>
</form>

I'm currently passing one value scname when submitting the form, I need to pass two values scname and desc and access them later

How can I send these two values

Upvotes: 0

Views: 1130

Answers (3)

cristian
cristian

Reputation: 526

You can also use json arrays if you need a simpler form:

<option value='[ "{{desc}}", "{{scname}}" ]'>{{desc}}/{{scname}}</option>

This will be serialized into a list in Python:

my_list = json.loads(request.POST.get('option'))
print(my_list[0])
print(my_list[1])

Upvotes: 1

Lal
Lal

Reputation: 1628

Hopefully it will work. You can pass a JSON string from option and convert json string to json object inside django view

<option value="{'desc': {{desc}}, 'scname': {{scname}} }">{{desc}}/{{scname}}</option>

and then inside your Django view function

import json
blocks = json.loads(request.POST.get('listxblocks'))
desc = blocks['desc']
scname = blocks['scname']

Upvotes: 2

Zartch
Zartch

Reputation: 1025

When i need to unpack two values i write both with a known separator:

<option name value="{{desc}}#{{scname}}">{{desc}}/{{scname}}</option>

then in your views:

foo = request.POST.get('listxblocks').split('#')
desc = foo[0]
scname = foo[1]

Upvotes: 2

Related Questions