Django模板搜索后输入框重置:如何设置input的value参数
Django搜索后保留表单输入内容的解决方法
要让搜索后输入框和下拉框保留用户之前的输入,你需要利用Django模板的request.GET对象,把用户提交的查询参数回填到表单控件里:
1. 处理输入框(input)
把value=""替换成value="{{ request.GET.控件name属性值 }}",比如:
- 关键词输入框(kword):
value="{{ request.GET.kword }}" - 位置输入框(location):
value="{{ request.GET.location }}"
当用户提交搜索后,request.GET会包含对应的参数值,模板会自动把值填充到输入框里;如果没有参数(比如首次加载页面),这个变量会输出空字符串,不影响默认显示。
2. 处理下拉选择框(select)
需要给匹配request.GET参数的选项添加selected属性,判断当前选项的value是否等于request.GET中对应的参数值。
比如type下拉框修改后:
<select name="type" id="type"> <option value="Todos" {% if request.GET.type == 'Todos' %}selected{% endif %}>Todos</option> <option value="Remoto" {% if request.GET.type == 'Remoto' %}selected{% endif %}>Remoto</option> <option value="Presencial" {% if request.GET.type == 'Presencial' %}selected{% endif %}>Presencial</option> </select>
sort下拉框修改后:
<select name="sort" id="sort"> <option value="relevance" {% if request.GET.sort == 'relevance' %}selected{% endif %}>Relevancia</option> <option value="date" {% if request.GET.sort == 'date' %}selected{% endif %}>Fecha</option> <option value="salary" {% if request.GET.sort == 'salary' %}selected{% endif %}>Salario</option> </select>
修改后的完整表单代码
<input id="kword" name="kword" value="{{ request.GET.kword }}" class="input-form search-box" type="search" placeholder="Profesión, palabra clave o empresa" data-ac="//ac.careerjet.net/ns" data-target="#ac-s" data-target2="#s" data-as="1" data-lc="es_MX" data-mhd="10" data-mhm="3" > <input id="location" name="location" value="{{ request.GET.location }}" class="input-form search-box" type="search" placeholder="Ubicacion" data-ac="//ac.careerjet.net/ns" data-target="#ac-s" data-target2="#s" data-as="1" data-lc="es_MX" data-mhd="10" data-mhm="3" > <select name="type" id="type"> <option value="Todos" {% if request.GET.type == 'Todos' %}selected{% endif %}>Todos</option> <option value="Remoto" {% if request.GET.type == 'Remoto' %}selected{% endif %}>Remoto</option> <option value="Presencial" {% if request.GET.type == 'Presencial' %}selected{% endif %}>Presencial</option> </select> <select name="sort" id="sort"> <option value="relevance" {% if request.GET.sort == 'relevance' %}selected{% endif %}>Relevancia</option> <option value="date" {% if request.GET.sort == 'date' %}selected{% endif %}>Fecha</option> <option value="salary" {% if request.GET.sort == 'salary' %}selected{% endif %}>Salario</option> </select>
注意:确保你的视图函数是通过GET方法处理搜索请求的,这样request.GET才能获取到用户提交的参数。
内容的提问来源于stack exchange,提问作者Lucin Husein
相关产品推荐
相关产品推荐

