我有一个视图,它从一个模型中获取两个对象,并返回由这两个对象组成的上下文和每个对象属性之间的差值列表。从网上看,在Django模板中索引这个列表的方法是通过简单的{difference.0},但是在我的例子中它不起作用,我不知道为什么。当在模板中将列表打印到屏幕上时,它只打印一个空列表,这意味着我传递的列表是空的。不过,我已经在shell中测试了我的代码,它生成了我想要的列表。我错过了什么?你知道吗
以下是我的观点:
def compare(request, champion1, champion2):
champion1_requested = get_object_or_404(Champion, name=champion1)
champion2_requested = get_object_or_404(Champion, name=champion2)
difference = []
list1 = Champion.objects.values_list('hp', 'hp5', 'hp5Plus').filter(name=champion1)
list2 = Champion.objects.values_list('hp', 'hp5', 'hp5Plus').filter(name=champion2)
for i in xrange(len(list1[0])):
#if isinstance(list1[i], (int, float, long, complex)):
difference.append(float(list1[0][i]))
context = {'champion1': champion1_requested,
'champion2': champion2_requested,
'difference': difference}
return render(request, 'ChampData/compare.html', context)
这是我的模板的一部分:
{% extends 'ChampData/theme.html' %}
{% block container %}
<h1 style="text-align: center;">Champion Comparison</h1>
{{ difference }}
{{difference}}
{{ difference.0 }}
{{ difference.2 }}
{% if champion1 %}
{% if champion2 %}
<table class="table table-hover">
<tr><th>Name:</th><td>{{ champion1.name }}</td><td>{{ champion2.name }}</td></tr>
<tr><th>Style:</th><td>{{ champion1.style }}</td><td>{{ champion2.style }}</td></tr>
<tr><th>Health:</th><td>{{ champion1.hp }}</td><td>{{ champion2.hp }}</td><td>{{ difference.0 }}</td></tr>
<tr><th>Health per level:</th><td>{{ champion1.hpPlus }}</td><td>{{ champion2.hpPlus }}</td><td>{{ difference.1 }}</td></tr>
<tr><th>Health Regen per 5:</th><td>{{ champion1.hp5 }}</td><td>{{ champion2.hp5 }}</td><td>{{ difference.2 }}</td></tr>
<tr><th>Health Regen per 5 per level:</th><td>{{ champion1.hp5Plus }}</td><td>{{ champion2.hp5Plus}}</td></tr>
表开头的“{difference}}”只打印“[]”,而“{difference.0}}”不打印任何内容,但下面是我在shell中对其进行的测试:
>>> list1 = Champion.objects.values_list('hp','hp5','hp5Plus').filter(name='Ahri')
>>> difference = []
>>> for i in xrange(len(list1[0])): difference.append(float(list1[0][i]))
...
>>> difference
[514.4, 6.505, 0.6]
所以,我不知道为什么它不起作用。任何帮助都将不胜感激。你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐