You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django的Views中获取HTML Select下拉框的选中值?

问题分析与解决方案

1. 核心问题点

  • 下拉框缺少name属性:Django的request.POST是通过表单元素的name属性取值的,你的下拉框只有id="drop1",没有name="drop1",导致后端无法获取到值。
  • 表单没有提交按钮:没有触发POST请求的入口,表单数据根本不会被提交到后端。
  • action属性配置:如果要提交到当前视图,可直接留空(action=""),或者填写对应视图的URL(比如用Django的{% url %}模板标签)。

2. 修改后的代码示例

index.html

<form action="" method="post">
    {% csrf_token %} <!-- 必须添加,防止CSRF攻击,Django要求POST表单必须包含这个 -->
    <select id="drop1" name="drop1"> <!-- 新增name属性 -->
        <option disabled selected value> -- select value -- </option>
        {% for i in df %}
        <option value="{{ i }}">{{ i }}</option>
        {% endfor %}
    </select>
    <button type="submit">提交</button> <!-- 新增提交按钮 -->
</form>

views.py

def index(request):
    if request.method == 'POST':
        selected_value = request.POST.get('drop1')
        print(selected_value)
        # 目前你的option的value和显示文本一致,所以selected_value就是显示文本
        return render(request, 'index.html', {'df': df.designation_list})
    else:
        return render(request, 'index.html', {'df': df.designation_list})

3. 若需获取与value不同的显示文本

如果以后你的option结构变成类似<option value="{{ i.id }}">{{ i.name }}</option>(value和显示文本不同),后端要获取显示文本的话,有两种可靠方式:

  • 方法一:后端通过拿到的value(比如i.id),从数据库或数据源中查询对应的显示文本,这是最安全的方式,避免前端篡改数据。
  • 方法二:用JS在提交前把显示文本存入隐藏input,随表单一起提交:
    在index.html中添加隐藏input:
    <input type="hidden" name="selected_text" id="selected_text">
    
    新增JS代码:
    const selectBox = document.getElementById('drop1');
    const hiddenTextInput = document.getElementById('selected_text');
    selectBox.addEventListener('change', function() {
        hiddenTextInput.value = this.options[this.selectedIndex].text;
    });
    
    后端即可通过request.POST.get('selected_text')拿到显示文本。

内容的提问来源于stack exchange,提问作者alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 11:15:37