Reputation: 1240
I have a very simple form with a "select" field. For each user in the app it creates an option field, that works fine:
<select name="users" id="users" multiple>
<option value="{{admin.id}}" selected>{{ admin.username }}</option>
<!-- can I delete the admin from this list? -->
{% for user in users %}
<option value="{{user.id}}">{{ user.username }}</option>
{% endfor %}
</select>
Now when I try to retrieve the values of "users", even if they are all selected I always just get a single value...:
if request.method == "POST":
title = request.POST["title"]
admin = request.user
project_users = request.POST["users"]
print(project_users)
I just get "1" or "2" but not a list? How can I retrieve all of the values from this multiple select?
Upvotes: 1
Views: 1196
Reputation: 477824
If you subscript request.POST
you get the last value that was matched with the given key, even if there are multiple.
You can make use of .getlist(…)
[Django-doc] to obtain a list of values. The list will be empty in case no values match with the given key:
if request.method == 'POST':
title = request.POST['title']
admin = request.user
project_users = request.POST.getlist('users')
print(project_users)
It might however be more convenient to work with forms [Django-doc] to validate and clean the request data.
Upvotes: 3