Serializing dictionary in Django to use with Dajaxice or ajax -
i'm trying write monitor site temperature devices gets updated every x seconds. far have function returns dictionary using dajaxice. ajax.py:
def temperature(request): temperature_dict = {} filter_device in temperaturedevices.objects.all(): get_objects = temperaturedata.objects.filter(device=filter_device) current_object = get_objects.latest('date') current_data = current_object.data temperature_dict[filter_device] = current_data table = str(temperature_dict) return simplejson.dumps({'table':table})
and callback:
function my_callback(data){ if(data!=dajaxice.exception){ document.getelementbyid('test').innerhtml = data.table; } else{ alert('error'); } } dajaxice.toolbox.monitor.temperature('my_callback');
originally, html looks this:
<div id="test"> <tr> {% label, value in table %} <td>{{ label }} </td> <td>{{ value }} </td> {% endfor %} </tr></div>
how can write can iterate through dictionary in dajax output similar have in original html using django? in advance.
i'm taking "using django" part of question mean you're not interested in using javascript generate necessary dom objects insert page.
as such, first thought have django template render in view , return in json. example, have template called '_data_table.html':
<tr> {% label, value in table %} <td>{{ label }}</td> <td>{{ value }}</td> {% endfor %} </tr>
your original html modified this:
<div id="test"> {% include '_data_table.html' %} </div>
and change view this:
from django.template.loader import render_to_string def temperature(request): temperature_dict = {} filter_device in temperaturedevices.objects.all(): get_objects = temperaturedata.objects.filter(device=filter_device) current_object = get_objects.latest('date') current_data = current_object.data temperature_dict[filter_device] = current_data table = render_to_string('_data_table.html', {'table': temperature_dict}) return simplejson.dumps({'table': table})
note: untested code :)
Comments
Post a Comment