Refreshing table with Dajaxice in Django

杀马特。学长 韩版系。学妹 提交于 2019-12-06 11:12:29

问题


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 write this so that my callback refreshes the table?


回答1:


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.



来源:https://stackoverflow.com/questions/3759210/refreshing-table-with-dajaxice-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!