ChemseddineZ
ChemseddineZ

Reputation: 1818

retrieve multiple values from Dropdown menu in Django

I have a form well rendered in my template with a dropdown menu and a save button, when i choose an item from the dropdown menu and click save, I pass to the views.py the url for that item, like this:

<select name="listxblocks">
  {% for scname, desc in scenarios %}
    <option value="{% url "workbench_show_scenario" scname %}">{{desc}}/{{scname}}</option>
  {% endfor %}
</select>

Now, in the views.py file i can retrieve the selected item and it's value,

if request.method == "POST": #checks if the request is a POST operation
    url = request.POST['listxblocks'] 

but i want also to retrieve the name scname and the description desc

I tried with hidden field but it made my template messy, how can i do that? Thanks!

Upvotes: 1

Views: 1318

Answers (1)

Mattia
Mattia

Reputation: 1129

There are two ways for retrive all information from your select.

1) Take all data from select. in the view use the following code:

variable = request.POST.getlist('listxblocks')

2) add "multiple" to your select like

<select name="listxblocks" multiple="multiple">
      {% for scname, desc in scenarios %}
      <option value="{% url "workbench_show_scenario" scname %}">{{desc}}/{{scname}}</option>
      {% endfor %}
    </select>

in view.py using

url = request.POST['listxblocks']

you will find a list with all selected options

Hope this helps :)

Upvotes: 1

Related Questions