新数据可用时自动刷新django表

时间:2017-05-22 13:14:31

标签: jquery python ajax django client-side

我已经实现了fetch_results函数,以便在django网站中向数据库添加新数据。每次刷新页面都会激活此功能。

views.py 

def fetch_results():
# global result
documents = DRSDocument.objects.all()

for doc in documents:
    computed_image_path = os.path.join(WORKING_DIRECTORY, doc.uuid, 'process_result.jpg')

    drs_status = doc.status
    if os.path.isfile(computed_image_path):

        if drs_status == 'Q':

            doc.date_process_end = timezone.now()
            doc.status = 'F'
            doc.save()
return render('list_admin.html', {'status': drs_status})

当服务器os.path.isfile(computed_image_path)中的图像可用时,django网页中提供了数据。

list_admin.html

<script>
function refresh() {
$.ajax({
url: '{% url table_monitoring %}',
success: function(data) {
var dtr = $("#container2c", data);
$('#container2c').html(dtr);
      }
  });
setTimeout("refresh()", 3000);
}

$(function(){
refresh();
});

</script>

{% endblock %}

{% block content %}
<div id="container2c" align="center">
<BR>
<BR>
    {% if drs_images %}
    <BR>
    <form method="post" action="{% url 'retinal_drs_delete_multiple' %}"     style="height: 530px;overflow-y: scroll;width: 90%;">
        {% csrf_token %}
        <table id="myTable" style="width:90%;font-style: normal;">
            <thead>
            <tr style="font-style: italic;">
                <th><div class="th-inner"><IMG title="Click to select all" width=12px src="{% static 'images/red-delete-button.png' %}" onclick="return selectAllForDeletion();"></IMG></div></th>
                <th><div class="th-inner">&nbsp;Image&nbsp;</div></th>
                <th><div class="th-inner">&nbsp;#&nbsp;</div></th>
            </tr>
            </thead>
        <tbody>

            {% include 'list_admin_table.html' %}

        </tbody>
    </table>
    <BR>
    <BR>
    <input type="submit" value="Delete selected">
    <BR>

    </form>

这是我的list_admin_table.html

list_admin_table.html

{% for document in drs_images %}
            <tr {% if document.completed %}style="color:white;    font-weight:bold;"{% else %}style="color: black;"{% endif %}>
                <td><INPUT type="checkbox" name="delete_{{    document.drs_image.uuid }}" id="id_delete_{{ document.drs_image.uuid }}"    value="true"/></td>
                <td><IMG WIDTH="22px" SRC="{% static 'images/' %}{{    document.drs_image.get_status_icon }}" title="{{ document.drs_image.get_status_display }}"> </td>
                <td>{{ forloop.counter }}</td>
            </tr>

        {% endfor %}

这是我的urls.py

    urlpatterns = [
        url(r'^list/$', retinal_drs_views.list_admin, name='retinal_drs_list_admin')
        url(r'^table-monitoring/$', retinal_drs_views.fetch_results, name="table_monitoring"),
]

我的目标是定期(每10秒)获取一次结果,如果返回true,则自动刷新table id="myTable"

我一直在阅读有关AJAX,Jquery,Websockets的信息......但我是django和客户端编程的新手,所以我没有得到任何有效的结果。

谢谢!

1 个答案:

答案 0 :(得分:0)

我检查了这个答案,基本上它也适合你 here