Reputation: 87
I'm trying to write a monitor site so the temperature for certain devices gets updated every x seconds. So far I have a function that returns a dictionary using dajaxice. This is my ajax.py:
def temperature(request):
temperature_dict = {}
for 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 this is my 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, my html looks like this:
<div id="test"> <tr>
{% for label, value in table %}
<td>{{ label }}
</td>
<td>{{ value }}
</td>
{% endfor %}
</tr></div>
How can I write this so I can iterate through the dictionary I get in dajax so that the output is similar to what I have in my original html using just django? Thanks in advance.
Upvotes: 0
Views: 852
Reputation: 725
I'm taking the "using just Django" part of your question to mean that you're not interested in using JavaScript to generate the necessary DOM objects to insert into the page.
As such, my first thought would be to have a Django template that you render in your view and return in your JSON. For example, say you have a template called '_data_table.html':
<tr>
{% for label, value in table %}
<td>{{ label }}</td>
<td>{{ value }}</td>
{% endfor %}
</tr>
Your original HTML could be modified to look like this:
<div id="test">
{% include '_data_table.html' %}
</div>
And you could change your view to look something like this:
from django.template.loader import render_to_string
def temperature(request):
temperature_dict = {}
for 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: This is untested code :)
Upvotes: 1