我的comments.html
子模板如下所示:
<div class="commentsContainer">
{% for comment in comment_list %}
...
{{ comment.text }}
...
{% endfor %}
</div>
当我点击一个按钮时,我称之为AJAX功能:
$('.comments_new').on('click', function() {
$.ajax({
type: 'GET',
url: '/new_comments/',
data: {
},
success: function (data) {
$('.commentsContainer ').replaceWith(data);
}
})
});
调用此视图来更改查询集(初始查询集为comment_list = Comment.objects.filter().order_by('-score__upvotes')
:
def new_comments(request):
if request.is_ajax():
comment_list = Comment.objects.filter().order_by('-timestamp')
html = {'comment_list': render_to_string('comments.html', {'comment_list': comment_list})}
return JsonResponse(html)
这成功交换了查询集,但由于某些原因,没有javascript可用于新加载的模板/查询集。有人可以告诉我为什么会发生这种情况以及如何解决这个问题?
PS:调用时,有时会在终端中出现此错误:UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.