Python 在搜索后将值保留在下拉列表中

Python 在搜索后将值保留在下拉列表中,python,django,Python,Django,我的页面上有一个过滤器,它按类别过滤我的项目。您可以从下拉列表中选择所需类别,然后按search,屏幕上将显示过滤后的内容。唯一的问题是,下拉列表会重置,并且不会显示当前项目所过滤的类别。有人知道怎么解决这个问题吗 views.py def HomeView(request): item_list = Item.objects.all() item_list = item_list.annotate( current_price=Coalesce('discount_pric

我的页面上有一个过滤器,它按类别过滤我的项目。您可以从下拉列表中选择所需类别,然后按search,屏幕上将显示过滤后的内容。唯一的问题是,下拉列表会重置,并且不会显示当前项目所过滤的类别。有人知道怎么解决这个问题吗

views.py

def HomeView(request):
  item_list = Item.objects.all()
  item_list = item_list.annotate(
      current_price=Coalesce('discount_price', 'price'))

  category_list = Category.objects.all()
  query = request.GET.get('q')

  if query:
      item_list = item_list.filter(title__icontains=query)

  cat = request.GET.get('cat')
  if cat:
      item_list = item_list.filter(category__pk=cat)

  price_from = request.GET.get('price_from')
  price_to = request.GET.get('price_to')

  if price_from:
      item_list = item_list.filter(current_price__gte=price_from)

  if price_to:
      item_list = item_list.filter(current_price__lte=price_to)

  paginator = Paginator(item_list, 10)

  page = request.GET.get('page')

  try:
      items = paginator.page(page)
  except PageNotAnInteger:
      items = paginator.page(1)
  except EmptyPage:
      items = paginator.page(paginator.num_pages)

  context = {
      'items': items,
      'category': category_list
  }
  return render(request, "home.html", context)
html:


类别
选择。。。
全部的
{%类别中的cat为%}
{{cat}}
{%endfor%}
搜寻

尝试将下拉列表的值设置为用户选择的值。 例如:如果我选择了“猫”,则将下拉列表的默认值更新为“猫”

基本上只需不断更新下拉列表的默认值,然后进行检查


希望有帮助!:)

在模板中,您可以将
选定的
属性添加到
请求.GET.cat
中的值中:

<option value="" {% if not request.GET.cat %} selected {% endif %}>Choose...</option>
{% for cat in category %}
   <option value="{{ cat.pk }}" {% if request.GET.cat == cat.pk|slugify %} selected {% endif %}>
      {{ cat }}
   </option>
{% endfor %}
选择。。。
{%类别中的cat为%}
{{cat}}
{%endfor%}

不起作用,搜索后返回“Choose..”@Menor哦,您还需要从Choose项目中删除所选内容。检查更新的答案。不幸的是,结果仍然相同,我甚至从“选择…”选项中删除了
selected
,但没有任何结果changed@Menor哎呀,你需要把pk转换成字符串。您可以为此使用
slagify
过滤器。再次检查更新:)
<option value="" {% if not request.GET.cat %} selected {% endif %}>Choose...</option>
{% for cat in category %}
   <option value="{{ cat.pk }}" {% if request.GET.cat == cat.pk|slugify %} selected {% endif %}>
      {{ cat }}
   </option>
{% endfor %}