[Answer]-Insert variables into a HTML template in Django view then return via AJAX

1👍

Sure. You can use render_to_string:

from django.template.loader import render_to_string

def getBlueWidgets(request):
    widgets = Widget.objects.filter(colour='blue')
    html = render_to_string('widgets.html', {'widgets': widgets})
    return HttpResponse(json.dumps(html), mimetype="application/json")

# widgets.html
{% for widget in widgets %}
    <div class="widget">
        <div class="title">{{ widget.title }}</div>
    </div>
{% endfor %}

Leave a comment