我想在stats.html文件中包括一些有关模型的基本统计信息。变量不会显示在html中。我在做什么错了?
from django.shortcuts import render, get_object_or_404, redirect
from django.db.models import Avg, Sum, Count
from .models import Production
def statistics(request):
nr_of_plays = Production.objects.count()
nr_of_actors = Production.objects.aggregate(num_actors=Sum('nr_actors'))
nr_of_audience = Production.objects.aggregate(num_audience=Sum('est_audience'))
context = {
'nr_of_plays': nr_of_plays,
'nr_of_actors': nr_of_actors['num_actors'],
'nr_of_audience': nr_of_audience['num_audience'],
'test':'abc'
}
return render(request, 'stats.html', context)
模型:
class Production(models.Model):
title = models.CharField(max_length=200)
nr_actors = models.IntegerField(default=0)
est_audience = models.IntegerField(default=0)
...
urls.py:
path('stats/', views.statistics, name='stats'),
base.html的相关部分:
<copyright class="text-muted">
<div class="container text-center">
<p>© One World Theatre - {% now "Y" %} {% include 'stats.html' with test=test %} </p>
</div>
</copyright>
还有stats.html模板:
{% load static %}
{{ test }} - Stats: {{ nr_of_plays }} plays produced, involving {{ nr_of_actors }} actors, seen by {{ nr_of_audience }} people.
输出: © One World Theatre - 2020 - Stats: plays produced, involving actors, seen by people.
编辑:
我没有提到我在stats.html
模板中使用模板base.html
像这样{% include 'stats.html' %}
。当我将with test=test
添加到include标记时,将显示测试文本。但是,当添加with nr_of_plays=nr_of_plays
时,什么也没有发生:-/。
我最终忘了尝试在我的基本模板中尝试{% include 'stats.html' %}
,只是将这些变量添加到需要的地方,效果很好。不是DRY,而是要怎么做...。
编辑2:
我哭得太快了。使用最新代码编辑了问题。在处理主要内容块的视图中传递变量是可行的,但这意味着我将不得不在每个视图中添加它们(不是DRY)。仍然没有得到我的设置不起作用的信息。 example.com/stats.html
可以完全呈现我想要的内容,但是当我在include
中base.html
时不显示变量。 with test=test
不执行任何操作。一无所知(感谢提供帮助的人)。
答案 0 :(得分:1)
Aggregate返回一个字典。
您需要通过密钥访问其值
context = {
'nr_of_plays': nr_of_plays,
'nr_of_actors': nr_of_actors['nr_actors_sum'],
'nr_of_audience': nr_of_audience['est_audience_sum']
}
或者,您可以指定自定义键名称,而不是默认的组合键名称:
nr_of_actors = Production.objects.aggregate(num_actors=Sum('nr_actors'))
nr_of_audience = Production.objects.aggregate(num_audience=Sum('est_audience'))
注意:.all()
是多余的,可以删除
答案 1 :(得分:1)
根据您最近的自白和症状,您似乎并没有进入statistics
视图。
好像url呈现了另一个视图,该视图还扩展了base.html
,使您误以为您在正确的视图中。
一种测试它的方法是在您的statistics
视图中放置一条打印语句,并查看它是否可以在控制台中打印任何内容:
def statistics(request):
print(111111111111111111111111111111)
...
return render(request, 'stats.html', context)
第二件事是,如果您的base.html
包含stats.html
,则不应直接呈现stats.html
,而应将上下文传递给扩展base.html
的模板
第三件事是,请参考Pynchia的答案以正确获取聚合查询集的数量。