views.py:-
def search(request):
global pro
global products
if not request.GET.get('price_filter') == '1' or request.GET.get('price_filter') == '2':
q = request.GET.get("q")
products = Product.objects.filter(active=True, name__icontains=q)
categories = Category.objects.filter(active=True)
brands = Brand.objects.filter(active=True)
context = {"products": products,
"categories": categories,
"brands": brands,
"title": q + " - search"}
return render(request, "shop/home.html", context)
pro = products
if request.GET.get('price_filter') == '1':
products = pro.order_by('price')
categories = Category.objects.filter(active=True)
brands = Brand.objects.filter(active=True)
context = {"products": products,
"categories": categories,
"brands": brands}
return render(request, "shop/home.html", context)
elif request.GET.get('price_filter') == '2':
products = pro.order_by('-price')
categories = Category.objects.filter(active=True)
brands = Brand.objects.filter(active=True)
context = {"products": products,
"categories": categories,
"brands": brands}
return render(request, "shop/home.html", context)
在HTML中:-
<form method='get' action='#' style="margin-top:-20px; margin-left: 8px;">
<input class="btn btn-outline-dark" type="checkbox" value="1" name="price_filter"/>Low to High
<input class="btn btn-outline-dark" type="checkbox" value="2" name="price_filter"/>High to Low
<button class="btn" type="submit" value="Sort">Sort</button>
</form>
使用该搜索,我们可以从低到高排序,但是当我选择从高到低时,它会显示某些错误:-
Cannot use None as a query value
我知道这不是执行此操作的正确方法,但是可以帮助我解决此问题,或者为我提供正确的排序方法。
此行发生此错误:
if not request.GET.get('price_filter') == '1' or request.GET.get('price_filter') == '2':
^^^
表示如果没有request.GET.get('price_filter')
的值而有request.GET.get('price_filter')
的值。我认为这里应该是这样的not子句:
if not request.GET.get('price_filter') == '1' or not request.GET.get('price_filter') == '2':
^^^
原因是,模板中没有q的输入字段。
此外,您也可以将querystring值存储在变量中,以使该代码更清晰:
price_filter = request.GET.get('price_filter')
if price_filter not in ["1", "2"]:
q = request.GET.get("q")
# rest of the code
elif price_filter == "1":
# more code
elif price_filter == "2":
# more code