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(无页面刷新)将{%forcomment\u li
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\u list
的值更改为等于comment.objects.filter().order\u by('-timestamp')
?当开发人员(您)这样说时,会发生AJAX请求。例如,如果您已将事件侦听器设置为“单击”特定按钮以发出AJAX请求,则将发出AJAX请求
假设您有一个事件侦听器,它使用id=my button
在特定按钮上“侦听”单击事件
{# Place this as a separate html file, say "ajax_comments.html" #}
<div id="my-placeholder">
{% for comment in comments %}
{{ comment }}
{% endfor %}
<button id="my-button">Update comments</button>
</div>
{# END OF PLACE THIS #}
{# ############################################################### #}
{# Begin of your main HTML template, say "my_template.html" #}
....
{% include 'path/to/ajax_comments.html' %}
....
// make an Ajax call (GET request) to the same url, using jQuery.
$(document).ready(function() {
$('#my-button').on('click', function() {
$.ajax({
'method': 'GET', // defaults to GET. Set POST if you like, but be aware of the CSRF token submission too!
'url': '.', // submit to the same url
'data': {}, // pass here any data to the server. You can omit it.
success: function(dataReturned) {
// This function will run when server returns data
$('#my-placeholder').replaceWith(dataReturned);
}
});
});
});
{# END OF "my_template.html" #}
该按钮已在模板中按下
向服务器发出AJAX请求
在视图中,处理此类请求并返回带有新查询集的HTML部分
此返回不会直接呈现给模板,而是转到等待此返回的$.ajax()
函数
一旦收到,它将执行我们编写的操作(用新数据替换div
)
希望这对你有帮助 谢谢你的回复。我已经设法使用与您非常相似的代码更改了queryset,但由于某些原因,没有javascript在新加载的子模板上工作。你知道为什么吗?我在这里问了一个问题:
def my_view(request):
if request.is_ajax():
# If you have passed any data through the 'data' property
#you can get it here, according to the method used.
my_data = request.GET.get('data-name')
comments = Comment.objects.filter().order_by('-timestamp')
# Note that we are passing the 'ajax_comments.html' template.
return render(request, 'ajax_comments.html', {'comments': comments})
comments = Comment.objects.filter().order_by('-score__upvotes')
return render(request, 'my_template.html', {'comments': comments})