首页 > 解决方案 > Django 3 Pass Get The Selected Value Dropdown 选择选项

问题描述

已选择 Django 下拉选项。在模板中获取数据并选择选项。我的代码是。视图.py

def home(request):

compType = Type.objects.all()

comptype = request.GET.get('comp_type')
context = {
    'compType': compType
}

return render(request, 'compapp/dashboard.html', context)

搜索.html

<div class="form-group">
<label>Type</label>
<select class="form-control select2" name="comp_type" style="width: 100%;">
  <!-- <option disabled="true" selected >Company Type</option> -->
  {% for i in compType %}
  <option value="{{ i }}" {% if request.GET.items == i %}selected{% endif %}>{{ i }}</option>
  {% endfor %}
</select>

标签: pythondjango

解决方案


假设您有一个表单(搜索表单),该用户填写并提交了该表单。您收到了此表单并进行了查询集,然后您想显示一个包含搜索结果的页面,并且该表单的字段也填充了选定的值。因此,您也必须将该值传递给结果页面!'request.GET.items' 无法正常工作。你应该做的是:如果有一个名为“dr_select”的字段,在views.py搜索功能中,你应该通过

 selected = get_object_or_404(Type, id==int(request.GET['dr_select']))

然后将“选定”传递给结果页面,然后在该模板中你可以做你想做的事。

{% for item in compType %}
     <option value="{{ item.id }}" 
     {% if selected == item %}selected{% endif %}>{{ item } </option> 
      {% endfor %}

*注意:因为我在'option'标签中使用'item.id'作为'value',所以在后端我也必须通过id过滤模型。


推荐阅读