如何访问通过AJAX响应返回到模板的Queryset-Django [英] How to access Queryset returned to template by AJAX response - Django
问题描述
我想使用ajax将查询集返回到模板.
I want to return a queryset to a template using ajax.
这是我在单独的js文件中的ajax函数:
this is my ajax function in a seperate js file:
$(document).ready(function(){
$("#data_to_plot_button").click(function(){
var serialized_data = $("#data_to_plot_form").serialize();
$.ajax({
url: $("data_to_plot_form").data('url'),
data: serialized_data,
type: 'post',
success: function(response){
$("#graph").append('<p>data returned successfuly</p>'); //this line is printed correctly.
$.each(response, function(i, val) {
$('graph').empty().append(
$('<li>').addClass('list-group-item list-group-item-success').text(val)
)
}); // this block adds nothing to the #graph div
}
})
});
});
和我的 views.py
:
def my_products(request):
queryset_list_intro_products = Intro_products.objects.all().order_by('title')
products = 0
if request.method == 'POST':
products_checkbox = request.POST.get('products')
if products_checkbox:
products = serializers.serialize('json', list(queryset_list_intro_products))
context = {
'products': products,
}
return JsonResponse(context, status=200)
return render(request, 'users/basket/my_products.html')
基于对此问题的答案,我尝试访问返回了 response
中的 products
.但是js代码没有为 #graph
div添加任何内容.
based on an answer to this question, I try to access the returned products
which is in response
. but the js code adds nothing to the #graph
div.
在chrome检查的网络标签的XHR部分中,ajax调用的状态为200,在预览部分中,我可以看到 products
如下:
in XHR section of network tab of inspects in chrome, the ajax call's status is 200 and in the preview section I can see the products
as following:
products:"[{" model":"products.intro_products","pk":5,"fields":{"products_intro":false,"ip_sensor_intro":false,"control_valve_intro":否,"water_quality_sensor_intro":否,"accessories_intro":是,"cover_intro":照片/产品/intro_cover/solutions.png",标题":附件",";:",描述":"
描述
products: "[{"model": "products.intro_products", "pk": 5, "fields": {"products_intro": false, "ip_sensor_intro": false, "control_valve_intro": false, "water_quality_sensor_intro": false, "accessories_intro": true, "cover_intro": "photos/products/intro_cover/solutions.png", "title": "Accessories", "subtitle": "", "description": "
description
如何在知道查询集的情况下访问ajax响应的字段?
How to access the fields of an ajax response knowing its a queryset?
推荐答案
您需要执行以下操作;
You need to do something like this;
from django.template.loader import render_to_string
if request.is_ajax():
html = render_to_string(
template_name="your seperate template where you want to display the queryset",
context=dict_of_items_to_be_passed_to_above_temp.
)
data_dict = {"html_from_view": html}
return JsonResponse(data=data_dict, safe=False)
这篇关于如何访问通过AJAX响应返回到模板的Queryset-Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!