开发者

Refreshing table with Dajaxice in Django

开发者 https://www.devze.com 2023-01-17 11:00 出处:网络
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 dajaxic

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})

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 writ开发者_StackOverflow中文版e this so that my callback refreshes the table?


Use something similar like this:

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)

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');
    }
}

Hope this help you.

0

精彩评论

暂无评论...
验证码 换一张
取 消