在 Django 中使用 Dajaxice 刷新表格 [英] Refreshing table with Dajaxice in Django
问题描述
我正在监控不同位置的温度.我将数据存储在模型中并设置了我的 views.py,但我想每 5 分钟刷新一次表.我是 ajax 和 dajaxice 的新手,我该如何编写函数以使其显示在 html 中?这是我的 views.py:
I'm monitoring the temperature for different locations. I have the data stored in a model and have set my views.py, but I would like to refresh the table every 5 minutes. I'm new to ajax and dajaxice, how can I write the function so it displays in html? this is my views.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
return render_to_response('temp.html', {'temperature': temperature_dict})
至于我目前所理解的内容,这可能是我的 ajax.py,我应该修改它以返回一个 simplejson 转储.如果我错了,请纠正我.这是我的 temp.html:
As for what I think I'm understanding so far, this could be my ajax.py, I should just modify it to return a simplejson dump. Please correct me if Im wrong. This is my temp.html:
<table id="tval"><tr>
{% for label, value in temperature.items %}
<td>{{ label }}</td>
<td>{{ value }}</td>
{% endfor %}
</tr></table>
这就是我卡住的地方.我怎样才能写这个以便我的回调刷新表?
Here is where I get stuck. How can I write this so that my callback refreshes the table?
推荐答案
使用类似的东西:
from django.template.loader import render_to_string
from django.utils import simplejson
from dajaxice.core import dajaxice_functions
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('temp.html', {'temperature': temperature_dict})
return simplejson.dumps({'table':table})
dajaxice_functions.register(temperature)
作为 JS 回调,将 'table' 分配给您的 html 容器...(这只是一个示例):
And as JS callback, assign 'table' to your html container... (It's only an example):
function my_callback(data){
if(data!=Dajaxice.EXCEPTION){
document.getElementById('your_table_container_id').innerHTML = data.table;
}
else{
alert('Error');
}
}
希望对你有帮助.
这篇关于在 Django 中使用 Dajaxice 刷新表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!