[Fixed]-How do I change my queryset using AJAX?

1👍

What I guess, you are trying to use comment_list when page renders and new_comment_list using ajax without modifying

{% for comment in comment_list %}
    {{ comment }} 
{%  endfor %}

The problem with your code is comment_list is a queryset and it is evaluated on the server side, when the page is rendered (after passing through Django template engine ).Javascript doesn’t understand queryset. It understands HTML or JSON. So, you have to modify your script so that it return HTML or JSON for ajax request.

I would suggest you re-write your view like:

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)

And write your frontend to generate this HTML code.
here is a link that gives more better explanation of rendering using ajax: Returning Rendered Html via Ajax

Leave a comment