Rendering JSON objects using a Django template after an Ajax call Rendering JSON objects using a Django template after an Ajax call python python

Rendering JSON objects using a Django template after an Ajax call


Hey thanks vikingosegundo!

I like using decorators too :-).But in the meanwhile I've been following the approach suggested by the snippet I was mentioning above. Only thing, use instead the snippet n. 942 cause it's an improved version of the original one. Here's how it works:

Imagine you have a template (e.g., 'subtemplate.html') of whatever size that contains a useful block you can reuse:

     ........    <div id="results">                  {% block results %}            {% for el in items %}                   <li>{{el|capfirst}}</li>            {% endfor %}        {% endblock %}          </div><br />     ........

By importing in your view file the snippet above you can easily reference to any block in your templates. A cool feature is that the inheritance relations among templates are taken into consideration, so if you reference to a block that includes another block and so on, everything should work just fine. So, the ajax-view looks like this:

from django.template import loader# downloaded from djangosnippets.com[942]from my_project.snippets.template import render_block_to_stringdef ajax_view(request):    # some random context    context = Context({'items': range(100)})    # passing the template_name + block_name + context    return_str = render_block_to_string('standard/subtemplate.html', 'results', context)    return HttpResponse(return_str)


Here is how I use the same template for traditional rendering and Ajax-response rendering.

Template:

<div  id="sortable">{% include "admin/app/model/subtemplate.html" %}</div>

Included template (aka: subtemplate):

<div id="results_listing">{% if results %}    {% for c in results %}        .....    {% endfor %}{% else %}

The Ajax-view:

@login_required@render_to('admin/app/model/subtemplate.html')#annoying-decoratordef ajax_view(request):    .....    return {         "results":Model.objects.all(),    }      

Of course you can use render_to_response. But I like those annoying decorators :D


There's no reason you can't return a rendered bit of HTML using Ajax, and insert that into the existing page at the point you want. Obviously you can use Django's templates to render this HTML, if you want.