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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 23:54:01