У меня есть фильтр на моей странице, который фильтрует мои товары по категории. Вы можете выбрать категорию из выпадающего списка, а затем нажать кнопку поиска, и отфильтрованный контент отобразится. Единственная проблема заключается в том, что выпадающий список сбрасывает и не показывает категорию, по которой текущие элементы фильтруются. Кто-нибудь знает, как решить эту проблему?
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:
<form method="GET" action=".">
<div class="form-group col-md-4">
<label for="category">Category</label>
<select id="cat" class="form-control" name="cat">
<option value="" selected>Choose...</option>
<option value="" href="/home">All</option>
{% for cat in category %}
<option value="{{ cat.pk }}">
{{ cat }}</option>
{% endfor %}
</select>
</div>
<button type="submit" class="btn btn-primary">Search</button>
</form>