Django - Rendering Inclusion Tag from a View

Viewed 3092

so I was wondering if you could return an inclusion tag directly from a view.

The page is a normal page with a list of items. The list of items is rendered using an inclusion tag. If an ajax request is made to the view, I want to return only what the inclusion tag would return so I can append it onto the page via javascript. Is something like this possible? Or should I architect this better?

6 Answers

Using inclusion tag with configurable template decorator provided by Gonz instead of default Django's inclusion tags you can write a helper in your view:

from django.template.loader import render_to_string
from home.templatetags.objectwidgets import object_widget

def _object_widget(request, obj):
    template, context = object_widget(RequestContext(request), obj)
    return render_to_string(template, context)

It's DRY and works with Django 1.3 (I haven't tested it with Django 1.4).

I use this technique to return search results rendered in HTML via JSON/AJAX calls (nothing better which I came up with).

Related