筛选数据时select字段提交后选中状态丢失,需保留request.GET对应选中值
问题解决:Select字段提交后无法保留选中状态
你的核心问题是模板中判断选中状态的GET参数名不匹配:
- 你的select标签
name属性是discount_type,但模板里用request.GET.status来做选中判断,提交后无法获取到对应参数,导致选中状态丢失,同时筛选逻辑也因为参数错误无法生效。
修改后的代码如下:
<label class="text-secondary">Discount Type</label> <select name="discount_type" class="form-control"> <option value="" class="text-center">Select Type</option> {% for i in type %} <option {% if i.0 == request.GET.discount_type %} selected {% endif %} value="{{ i.0 }}">{{ i.1 }} </option> {% endfor %} </select>
额外补充优化建议:
- 为避免参数不存在时抛出
KeyError,可以改用get方法设置默认空值,判断部分可修改为:{% if i.0 == request.GET.get('discount_type', '') %} selected {% endif %} - 同时确保后端视图中,是通过
request.GET.get('discount_type')来接收参数并执行数据筛选逻辑,这样提交表单后才能正确显示筛选结果。
内容的提问来源于stack exchange,提问作者Shaiful Islam
相关产品推荐
相关产品推荐

