1👍
✅
From the code you’ve posted something like below should work…
in views.py:
from django.http import HttpResponse
from netadmin.plugins.templatetags.widgets import render_widget
def ajax_render_data(request, object_id):
return HttpResponse(render_widget(object_id))
in your django template:
(you said you want several of these on the page, so I’m going to use a loop in the django template, I don’t know what your widget collection is called but I’m sure you can work it out for your particular case)
<div class="widgets-container">
{% for widget_settings in widgetsettings.objects.all %}
<div class="widget-content" id="widget-content-{{ widget_settings.pk }}">
not loaded yet
</div>
{% endfor %}
</div>
<script>
// here we use django to render the ajax urls into an object
// in javascript so we can use it on the client side
var ajax_urls = {
{% for widget_settings in widgetsettings.objects.all %}
"{{ widget_settings.pk }}: "{% url ajax_render_data widget_settings.pk %}"{% if not forloop.last %},{% endif %}
{% endfor %}
};
// (I'll assume you're using jQuery)
// start the ajax calls when the page is loaded:
$(document).ready(loadWidgets());
function loadWidgets() {
// loop over the urls we provided from django:
jQuery.each(ajax_urls, function(widget_id, url) {
// do the ajax call:
$.get(url, function(data) {
// put the content into the widget div:
$('#widget-content-'+widget_id).html(data);
});
});
}
</script>
in urls.py:
urlpatterns += patterns('netadmin.plugins.ajax_view',
url(r'^ajax/(?P<object_id>\d+)/$', 'ajax_render_data', name='ajax_render_data'),
)
Source:stackexchange.com