javascript - 如何在 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 没有很好的了解,但我知道借助它可以实现。谁能指导我如何在不刷新页面的情况下呈现内容?
解决方案
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.
推荐阅读
- python - 无法从 django rest 框架 url 获取图像
- python - 更改 gnu radio 中每个脉冲的中心频率
- node.js - async.series 函数无法访问容器类的成员
- git - 将存储库推送到本地 GitLab 时遇到超时
- python - For 循环创建列表以附加到其他列表
- php - PHP使用正则表达式从字符串中提取所有日期
- azure - 向 Microsoft 团队发送应用程序洞察警报
- javascript - 在 Selenium Chrome 中使用 BAS 指纹
- javascript - 在 HTML 页面中制作相同的页眉和页脚,当它们被放置在不同的文件夹中时 - 图像消失了
- html - 将 HTM 文件用于 Outlook 签名