python - 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>
解决方案
假设您有一个表单(搜索表单),该用户填写并提交了该表单。您收到了此表单并进行了查询集,然后您想显示一个包含搜索结果的页面,并且该表单的字段也填充了选定的值。因此,您也必须将该值传递给结果页面!'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过滤模型。
推荐阅读
- snowflake-cloud-data-platform - 我们如何找到雪花中的学分余额?
- protocol-buffers - CloudEvents 在 gRPC 框架上有用吗?
- python - Exploding a key not present in JSON in PySpark
- java - 删除特定图例 apache poi excel 图 XDDFChartLegend
- python - 如何根据文本中的前三个数字找到一个 10 位数字?Python
- reactjs - 将功能组件转换为类组件react js
- javascript - 固定 div 中的文本溢出
- c - 使用缓冲区溢出覆盖函数返回地址
- python - Python3.8:十进制整数文字中的前导零是不允许的;对八进制整数使用 0o 前缀
- c# - 如何在接口中调用带有主体的方法