假设我在模板中显示了一个Django查询集,其中包含以下视图...
def objects_view(request):
user = request.user
query = request.GET.get('q')
objects = Product.objects.filter(title = q)
context = {'user':user,'query':query,'objects':objects}
return render(request, 'template.html', context)
然后当用户更改最小或最大价格的值时,将调用template.html中的Ajax函数...
$('#apply-price-changes').click(function(){
var Url = window.location.path; # Calling the same URL so we are POSTing to the same view
var priceMin = $('#price-min-hidden').val();
var priceMax = $('#price-max-hidden').val();
$.ajax({
async:true,
method:'POST',
url:Url,
data:{
'minPrice':priceMin,
'maxPrice':priceMax,
},
dataType:'json',
success:function(data){
console.log(data) # <- This logs all of the filtered objects (in JSON format) in the console
# Not sure what I'd write to go here, this bit is the problem
},
error:function(error){
console.log(error)
}
})
});
所以现在我认为我提供了一个POST请求来获取最低和最高价格值......
def objects_view(request):
user = request.user
query = request.GET.get('q')
objects = Product.objects.filter(title = q)
if request.method == 'POST':
minPrice = request.POST.get('minPrice')
maxPrice = request.POST.get('maxPrice')
objects = Product.objects.filter(title = q, price__gte = minPrice, price__lte = maxPrice)
data = serializers.serialize('json',objects)
return HttpResponse(json.dumps(data), content_type='application/json')
context = {'user':user,'query':query,'objects':objects}
return render(request, 'template.html', context)
现在,我希望将数据的结果显示在模板中,以便用户可以查看仅与已过滤的查询集匹配的产品,并且还可以执行一些“如果&#39;包含该数据的陈述。
HTML模板示例:
{% if objects.count > 0 %}
{% for object in objects %}
<h3>{{ object.title }}</h3>
<h4>{{ object.description }}</h4>
<h4>{{ object.price }}</h4>
{% endfor %}
{% else %}
No objects to display!
{% endif %}
如果还有我应该展示的代码,请告诉我。请注意,我不想打印从JSON返回的每一部分信息,例如每个对象的主键。
谢谢!