我正在尝试创建一个电子商务网站。所以,我试图添加过滤器,如价格:低到高反之亦然。我知道如何过滤价格,但我不知道如何在选择值发生变化时应用过滤器。
这是HTML代码
<div class="d-flex flex-row-reverse" style="margin-right: 20px; margin-bottom: 20px;">
<label>
<select class="bg-dark" name="price" id="priceFilter">
<option value="normal">Sort by Price</option>
<option value="low">Low-to-High</option>
<option value="high">High-to-Low</option>
</select>
</label>
</div>
<<p>Django代码/strong>def index(request):
fil = request.GET('price')
if fil == "low":
products = Product.objects.all().order_by('productDiscountedPrice')
elif fil == "high":
products = Product.objects.all().order_by('-productDiscountedPrice')
else:
products = Product.objects.all()
context = {
'products': products
}
return render(request, "Amazon/index.html", context)
那么,当select tag
值发生变化时,如何对产品进行排序?
-
如果不想重新加载页面,则需要使用ajax。这是ajax教程的链接。
-
将这个jquery链接包含在主html页头标签中。
<script> $('#priceFilter').on('change', 'input, select', function(event){ // id = this.id; // you can use this.id to get the corresponding id. var word = $("#priceFilter").val(); $.ajax({ type: 'GET', url: '{% url <YOUR DJANGO INDEX VIEW URL NAME> %}', data: { word: word, }, success: function (response) { console.log(response); // print response.content and response.data to see the data in the console. And later you can use those data in template using javascript. }, error: function (error_data) { console.log(error_data) } }); } </script>
在views.py中,像这样修改视图:
from django.shortcuts import render
from django.http import JsonResponse
def index(request):
fil = request.GET('price')
if fil:
if fil == "low":
products = Product.objects.all().order_by('productDiscountedPrice')
elif fil == "high":
products = Product.objects.all().order_by('-productDiscountedPrice')
else:
products = Product.objects.all()
context = {
'products': products
}
return JsonResponse(context)
else:
context = {}
return render(request, "Amazon/index.html", context)