Django价格排序表单提交刷新后下拉菜单选中项复位问题
解决步骤
1. 调整视图函数,传递当前选中的排序参数到模板
原视图存在逻辑缺陷:仅当价格区间参数转换整数失败时才会执行排序逻辑,正常输入价格区间后不会触发排序,同时没有把当前选中的排序值传递给模板。修改后代码如下:
def sortView(request): items = Item.objects.all() # 先获取当前排序参数,默认值设为你需要的默认选项,这里示例用v1 sorting_method = request.GET.get('select', 'v1') if request.method == "GET": min_price = request.GET.get('min-price') max_price = request.GET.get('max-price') # 处理价格区间过滤 if min_price and max_price: try: min_price = int(min_price) max_price = int(max_price) items = items.filter(price__gte=min_price, price__lte=max_price) except ValueError: pass # 统一处理排序,不管有没有走价格过滤都会生效 if sorting_method == 'v1': items = items.order_by('price') elif sorting_method == 'v2': items = items.order_by('-price') # 将当前排序值加入模板上下文 return render(request, 'shop/sort.html', {'items': items, 'current_sort': sorting_method})
2. 修改模板的下拉菜单,自动匹配选中项
在每个option标签中加模板判断,和后端传入的current_sort匹配时自动添加selected属性:
<label class="sort__dropdown" for="cars">Sorting method</label> <select name="select"> <option value="v1" {% if current_sort == 'v1' %}selected{% endif %}>Price: low to high</option> <option value="v2" {% if current_sort == 'v2' %}selected{% endif %}>Price: high to low</option> </select> <button class="sort__submit">SORT</button>
实现原理
模板渲染时会根据后端传入的当前排序值,给匹配的选项加上selected属性,浏览器加载页面时就会默认选中该选项,不会自动重置为默认值。
内容的提问来源于stack exchange,提问作者user16476339
相关产品推荐
相关产品推荐

