Django:在使用动态数据从视图呈现模板之后,模板保持静态,并且在将数据添加到数据库时不会更改
在my views.py中,我有以下代码Django:在使用动态数据从视图呈现模板之后,模板保持静态,并且在将数据添加到数据库时不会更改,django,dynamic-data,Django,Dynamic Data,在my views.py中,我有以下代码 from .forms import * from students.models import Student from classes.models import Class from venues.models import Venue from courses.models import Course from registrations.models import Registration class Test(View): temp
from .forms import *
from students.models import Student
from classes.models import Class
from venues.models import Venue
from courses.models import Course
from registrations.models import Registration
class Test(View):
template_name = "test.html"
context = {}
data_summary = {
"total_students": Student.objects.all().count(),
"total_classes": Class.objects.all().count(),
"total_courses": Course.objects.all().count(),
"total_registrations": Registration.objects.all().count(),
}
def get(self,*args, **kwargs):
return render(self.request,self.template_name,self.data_summary)
在my test.html中,我有以下内容:
<...snip ...>
<h3> Totals: </h3>
<hr>
</div>
<div class="row">
<div class="col-md-2 text-right">
<label style="color: Blue; font-size:24"> Students: </label>
</div>
<div class="col-md-2 text-right">
{% if total_students %}
总数:
学生:
{如果学生总数为%}
模板呈现得非常好,但如果我更新数据库并添加另一个学生和/或类并重新加载页面,字典中的数据不会更新
我不知道为什么数据没有更新。我现在很头痛,也不是70年代的好方法。在您的情况下,
数据摘要是一个类属性,在第一次声明测试时创建(在模块加载时)
您可以将其移动到get
方法,并确保每当页面get
发生时,数据库调用都会发生
def get(self,*args, **kwargs):
data_summary = {
"total_students": Student.objects.all().count(),
"total_classes": Class.objects.all().count(),
"total_courses": Course.objects.all().count(),
"total_registrations": Registration.objects.all().count(),
}
return render(self.request,self.template_name,data_summary)
既然已经解释过了,那就完全有道理了。多谢各位。