首页 > 解决方案 > 如何在 Django 中自动更新模板?

问题描述

考虑我有一个这样的基本模型:

class Text(models.Model):
    msg = models.TextField()

我正在渲染一个模板,例如:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <h1>Messages<h2><br>
        {% for message in messages %}
            <a> {{forloop.counter}} - {{message}} <br>
        {% endfor %}
</body>
</html>

带有相应的视图:

from django.shortcuts import render
from .models import Text

def home(request):
    context = {
        "messages": Text.objects.all(),
    }
    return render(request, 'app/home.html', context)

假设我正在Text通过管理页面创建新对象。如果我保存一个对象,我想在不刷新页面的情况下渲染它。我对 Javascript/jQuery/AJAX 没有很好的了解,但我知道借助它可以实现。谁能指导我如何在不刷新页面的情况下呈现内容?

标签: javascriptpythonjquerydjangoajax

解决方案


In such situation, polling is first option that comes to my mind. What you do is make a view which returns JsonResponse. Hope you know how to return queryset object by JsonResponse view

In straight forward way, allow view to return Text.objects.all(), before that you need to make queryset object serializable. In optimize way, you could check if model(Table) entries are really modified, if yes then send modified entries only, or all entries for simplicity.

suppose you have this structure in html

<div>
        <h1>Messages<h2><br>
        <div id = "msg-block">
            <a></a>
        </div>
</div>

on of ajax point of view, do this

function update_messages(data){
     // suppose msg-block, is id of div enclosing all links, header div is sepreate
     str = ""
     for(var i = 0; i < data.length; i++){
         str += `<a> ${data[i]} </a>`
     }
    $("#msg-block").html(str)

}

setInterval(function() {
     $.ajax({
                type: "POST",
                url: "<url-to-json-view>",           
                data : {csrfmiddlewaretoken:document.getElementsByName('csrfmiddlewaretoken')[0].value},
                success: function(data)
                {
                    console.log("Success  : ", data)
                    // function to update the table
                    update_messages(data)
                },
                error: function(request, status, error)
                {
                    alert(request.responseText);
                }
            });  
}, time-interval-in-ms)

enclose this in script tag, in your webpage and in normarl case to fetch data through ajax call.


推荐阅读