在 Django 中,多个 select 输入只是 returns 一个值?
in Django, multiple select input just returns a single value?
我有一个带有“select”字段的非常简单的表单。它为应用程序中的每个用户创建一个选项字段,效果很好:
<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>
现在,当我尝试检索“用户”的值时,即使它们都是 selected,我也总是只得到一个值...:[=14=]
if request.method == "POST":
title = request.POST["title"]
admin = request.user
project_users = request.POST["users"]
print(project_users)
我只得到“1”或“2”但不是列表?如何从这个多个 select?
中检索所有值
如果你下标 request.POST
你会得到与给定键匹配的最后一个值,即使有多个。
您可以使用 .getlist(…)
[Django-doc] 来获取值列表。如果没有值与给定键匹配,列表将为 空 :
if request.method == 'POST':
title = request.POST['title']
admin = request.user
project_users = request.POST<b>.getlist('users')</b>
print(project_users)
不过,使用 forms [Django-doc] 验证和清理请求数据可能会更方便。
我有一个带有“select”字段的非常简单的表单。它为应用程序中的每个用户创建一个选项字段,效果很好:
<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>
现在,当我尝试检索“用户”的值时,即使它们都是 selected,我也总是只得到一个值...:[=14=]
if request.method == "POST":
title = request.POST["title"]
admin = request.user
project_users = request.POST["users"]
print(project_users)
我只得到“1”或“2”但不是列表?如何从这个多个 select?
中检索所有值如果你下标 request.POST
你会得到与给定键匹配的最后一个值,即使有多个。
您可以使用 .getlist(…)
[Django-doc] 来获取值列表。如果没有值与给定键匹配,列表将为 空 :
if request.method == 'POST':
title = request.POST['title']
admin = request.user
project_users = request.POST<b>.getlist('users')</b>
print(project_users)
不过,使用 forms [Django-doc] 验证和清理请求数据可能会更方便。