Python 如何使用AJAX更改查询集?
我希望能够在不刷新页面的情况下更改我的评论查询集。以下是查询集:Python 如何使用AJAX更改查询集?,python,ajax,django,django-queryset,Python,Ajax,Django,Django Queryset,我希望能够在不刷新页面的情况下更改我的评论查询集。以下是查询集: comment_list = Comment.objects.filter().order_by('-score__upvotes') new_comments_list = Comment.objects.filter().order_by('-timestamp') 那么我的模板是 {% for comment in comment_list %} {{ comment }} ... 有没有办法使用AJAX(无页
comment_list = Comment.objects.filter().order_by('-score__upvotes')
new_comments_list = Comment.objects.filter().order_by('-timestamp')
那么我的模板是
{% for comment in comment_list %}
{{ comment }}
...
有没有办法使用AJAX(无页面刷新)将{%forcomment\u list%}中的注释更改为{%forcomment\u comments\u list%}
或者可能将comment_list
的值更改为等于comment.objects.filter().order_by('-timestamp')
编辑
视图:
ajax调用:
$('.comments_new').on('click', function() {
$.ajax({
type: 'GET',
url: '/new_comments/',
data: {
csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(),
},
success: function (data) {
console.log(data.comment_list); // undefined
}
})
});
我猜,您正在尝试在页面呈现时使用注释列表,而使用ajax创建新的注释列表,而无需修改
{% for comment in comment_list %}
{{ comment }}
{% endfor %}
代码的问题在于注释列表是一个查询集,在呈现页面时(通过Django模板引擎后),会在服务器端对其进行评估。Javascript不理解查询集。它理解HTML或JSON。所以,您必须修改您的脚本,以便它为ajax请求返回HTML或JSON
我建议您重新编写您的观点,如:
from django.template.loader import render_to_string
if request.is_ajax():
new_comments_list = Comment.objects.filter().order_by('-timestamp')
# you can keep your_div_template as a included template in your main template
html = render_to_string('your_div_template', {'comment_list': new_comments_list})
return HttpResponse(html)
并编写前端以生成此HTML代码。
这里有一个链接可以更好地解释如何使用ajax进行渲染:您可以在编辑中查看我的代码吗?我使用了你的方法,但似乎我没有在我的前端接收到呈现的查询集(返回未定义),我还得到了一个UserWarning:模板中使用了{%csrf_token%},但上下文没有提供值。这通常是由于不使用RequestContext造成的。
您应该非常清楚的是,您得到的是一小块HTML。需要用注释生成div替换的是同一个HTML。我想说,数据是需要用注释生成div替换的HTML。这可以用$('#div_id').HTML(数据)完成。您不必担心csrf,如果您不是从ajax生成表单,我怀疑您为什么会担心csrf。
from django.template.loader import render_to_string
if request.is_ajax():
new_comments_list = Comment.objects.filter().order_by('-timestamp')
# you can keep your_div_template as a included template in your main template
html = render_to_string('your_div_template', {'comment_list': new_comments_list})
return HttpResponse(html)