无法分析余数:“[plant\u id]”来自“total\u ecof[plant\u id]”

2024-09-28 21:50:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我的视图.py

def home(request):
    if not request.user.is_authenticated():
        template = 'data/login.html'
        return render(request, template)
    else:
            plants = Plant.objects.filter(user=request.user)
            total_ecof = []
            total_ectr = []
            for plant in plants:
                x = 0
                y = 0
                for recording in Recording.objects.filter(plant__id=plant.id):
                    x += (recording.time_to_detect * recording.performance_loss) / (
                    plant.nominal_power * recording.years_of_operation)
                    y += ((10 + 15 + 200 + 50) * plant.no_modules + 240 * 50 * recording.occurrence * plant.no_modules) / (
                         plant.nominal_power * 3)
                total_ecof.append(x)
                total_ectr.append(y)
        template = 'data/home.html'
        context = {
                    'plants':plants,
                    'total_ecof':total_ecof,
                    'total_ectr':total_ectr,
                    }
        return render(request, template, context)

我的html模板

{% for plant in plants %}
    <tr>
       <td>{{ plant.management_company }}</td>
       <td>{{ plant.plant_name }}</td>
       <td>{{total_ecof[plnat.id]}}</td>
    </tr>
{% endfor %}

但我得到了一个错误:

Exception Type: TemplateSyntaxError
Exception Value: Could not parse the remainder: '[plant.id]' from 'total_ecof[plant.id]'

我不明白为什么。我做错什么了?你知道吗

此外,请你帮我创建一个条形图,其中x轴是植物,y轴是相应的总生态足迹。你知道吗


Tags: inidhomeforrequesthtmltemplatetd
2条回答

@Exprator和@Daniel谢谢你的评论。我找到了解决办法:

首先在我的型号.py我在课堂上增加了以下内容:

def total_ecof(self):
    return self

然后我改变了我的视图.py

def home(request):
    if not request.user.is_authenticated():
        template = 'data/login.html'
        return render(request, template)
    else:
            plants = Plant.objects.filter(user=request.user)
            for plant in plants:
                plant.total_ecof = 0
                for recording in Recording.objects.filter(plant__id=plant.id):
                    plant.total_ecof += (recording.time_to_detect * recording.performance_loss) / (plant.nominal_power * recording.years_of_operation)
        template = 'data/home.html'
        context = {
                    'plants':plants
                    }
        return render(request, template, context)

以及我的html:

{% for plant in plants %}
    <tr>
       <td>{{ plant.management_company }}</td>
       <td>{{ plant.plant_name }}</td>
       <td>{{ plant.total_ecof }}</td>
    </tr>
{% endfor %}

我不知道这是否是最好的解决方案,但它是工作:)谢谢你们!!!!!你知道吗

不要为总数创建单独的列表。创建一个由(record,total)对组成的列表,或者直接在录制实例上设置total。你知道吗

相关问题 更多 >