django-last标记对象不可下标



我很抱歉问你,但。。。

我一直在用Django框架在HTML中尝试这个"最后"标签,以使数据库中的最后一个对象显示在我的HTML上;此处文档:https://docs.djangoproject.com/en/2.1/ref/templates/builtins/

现在的问题是当我在代码上使用"last"标记时;

<div class = "float-right  my-4 chartjs-render-monitor" id="chartContainerPH" style="width: 49%; height: 400px;display: inline-block; background-color:#FDFDFD;">
<center>
<a class="title-link" href="{%url 'ph' %}">PH:</a>
<p> {% for tank_system in tank %}{{tank_system.PH|last}}, {%endfor%}</p>
</center>
</div>

并得到这些错误;

TypeError at /
'decimal.Decimal' object is not subscriptable
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 2.1.3
Exception Type: TypeError
Exception Value:    
'decimal.Decimal' object is not subscriptable
Exception Location: C:UsersuserAppDataLocalProgramsPythonPython37-32libsite-packagesdjangotemplatedefaultfilters.py in last, line 540
Python Executable:  C:UsersuserAppDataLocalProgramsPythonPython37-32python.exe
Python Version: 3.7.1
Python Path:    
['C:\Users\user\Desktop\FrounterWeb- postgreDB',
'C:\Users\user\AppData\Local\Programs\Python\Python37-32\python37.zip',
'C:\Users\user\AppData\Local\Programs\Python\Python37-32\DLLs',
'C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib',
'C:\Users\user\AppData\Local\Programs\Python\Python37-32',
'C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages']
Server time:    Thu, 6 Dec 2018 11:12:47 +0800

我不清楚这些错误,但即使在阅读了这里之后:在Python中,如果一个对象是可下标的或不可下标的,这意味着什么?

这是我的模型代码;

from django.db import models
from django.utils import timezone
# having errors KeyError: "'__name__' not in globals"
class tank_system(models.Model):
PH = models.DecimalField(max_digits=3, decimal_places=1)
EC = models.DecimalField(max_digits=3, decimal_places=1)
WaterLevel = models.IntegerField(default=100)
TempWater = models.IntegerField(default=0)
TempRoom = models.IntegerField(default=0)
datetime = models.DateTimeField(default=timezone.now())

def get_last(self):
try:
print(self)
return self.set.all().order_by('-date')[0]
except IndexError:
pass

这里是我的观点代码;

from django.shortcuts import render
from django.views.generic import TemplateView
from zigview.models import tank_system
from django.contrib.auth.decorators import login_required
import logging
logger = logging.getLogger(__name__)
from django.core.mail import send_mail

try:
@login_required(login_url='/accounts/login/')
def index(request): #gose to main dashboard page
#tank = tank_system.objects.all()
tank = tank_system.objects.extra(select={'is_recent':"datetime>'2006-01-01'"})
return render(request,'FrounterWeb/extends/includes.html',{'tank':tank})
except:
logger.error('index page request failed/errors')

我很抱歉问

您可以测试for循环是否引用了带有forloop.last的最后一个项目,然后在上面查找PH属性:

<center>
<a class="title-link" href="{%url 'ph' %}">PH:</a>
<p> 
{% for tank_system in tank %}
{% if forloop.last %}
{{ tank_system.PH }}, 
{% endif %}
{% endfor %}
</p>
</center>

似乎在tanks的查询集上尝试使用Django的last模板标记会出现"不支持负索引"错误。

最新更新