我有这个urls.py文件:

...

urlpatterns = [
    path('region_service_cost/<str:region>/', views.region_service_cost, name='region_service_cost'),
    path('monthly-region-service-cost/<str:region>/', views.monthly_region_service_cost, name='monthly-region-service-cost')
]

我有这个views.py文件:

# Create your views here.
from django.shortcuts import render
from django.http import JsonResponse
from .models import MonthlyRegionServiceCost

def region_service_cost(request, region):
    return render(request, 'region-service-cost.html')

def monthly_region_service_cost(request, region='global'):
    colors = ['#DFFF00', '#FFBF00', '#FF7F50', '#DE3163', '#9FE2BF', '#40E0D0', '#6495ED', '#CCCCFF', '#9CC2BF',
              '#40E011', '#641111', '#CCCC00']
    labels = [ym['year_month'] for ym in MonthlyRegionServiceCost.objects.values('year_month').distinct()][:12]
    datasets = []

    for ym in labels:
        for i, obj in enumerate(MonthlyRegionServiceCost.objects.filter(region=region, year_month=ym)):
            dataset = {
               'label': obj.service,
               'backgroundColor': colors[i % len(colors)],
               'data': [c.cost for c in MonthlyRegionServiceCost.objects.filter(service=obj.service, region=region)]
            }
            datasets.append(dataset)


    return JsonResponse(data={
        'labels': labels,
        'datasets': datasets
    })

下面是我的区域服务-成本.html文件:

{% extends 'base.html' %}

{% block content %}

  <div id="container" style="width: 75%;">
    <canvas id="monthly-region-service-cost" data-url="{% url 'monthly-region-service-cost' region=region %}/{{ region | urlencode }}/"></canvas>

  </div>

  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

  <script>

    $(function () {

      var $productCostChart = $("#monthly-region-service-cost");
      $.ajax({
        url: $productCostChart.data("url"),
        success: function (data) {
          console.log(data);

          var ctx = $productCostChart[0].getContext("2d");

          new Chart(ctx, {
            type: 'bar',
            data: { labels: data.labels, datasets: data.datasets, },
            options: {
                plugins: { title: { display: true, text: 'Stacked Bar chart for pollution status' }, },
                scales: { x: { stacked: true, }, y: { stacked: true } }
            }
          });

        }
      });

    });

  </script>

{% endblock %}

当我把浏览器设置为http://127.0.0.1:8000/region_service_cost/global/时,我得到这样的输出:

NoReverseMatch at /region_service_cost/global/
Reverse for 'monthly-region-service-cost' with keyword arguments '{'region': ''}' not found. 1 pattern(s) tried: ['monthly\\-region\\-service\\-cost/(?P<region>[^/]+)/\\Z']
Request Method: GET
Request URL:    http://127.0.0.1:8000/region_service_cost/global/
Django Version: 4.2.10
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'monthly-region-service-cost' with keyword arguments '{'region': ''}' not found. 1 pattern(s) tried: ['monthly\\-region\\-service\\-cost/(?P<region>[^/]+)/\\Z']
Exception Location: /Users/russell.cecala/COST_REPORTS/django/cost_explorer/venv/lib/python3.9/site-packages/django/urls/resolvers.py, line 828, in _reverse_with_prefix
Raised during:  monthly_cost.views.region_service_cost
Python Executable:  /Users/russell.cecala/COST_REPORTS/django/cost_explorer/venv/bin/python
Python Version: 3.9.6

推荐答案

views.pyregion_service_cost()函数替换为:

def region_service_cost(request, region):
    return render(request, 'region-service-cost.html', {
        "region": region
    })

代码的问题在于您没有将区域传递给您的HTML页面,因此它不知道这一行中region的含义:

<canvas id="monthly-region-service-cost" data-url="{% url 'monthly-region-service-cost' region=region %}/{{ region | urlencode }}/"></canvas>

这一解决方案适用于任何地区,包括全球.

Python相关问答推荐

大Pandas 胚胎中产生组合

时间序列分解

rame中不兼容的d类型

处理(潜在)不断增长的任务队列的并行/并行方法

图像 pyramid .难以创建所需的合成图像

Python键入协议默认值

ThreadPoolExecutor和单个线程的超时

python中字符串的条件替换

提取相关行的最快方法—pandas

在Python中使用if else或使用regex将二进制数据如111转换为001""

如何在Python 3.9.6和MacOS Sonoma 14.3.1下安装Pyregion

无法在Spyder上的Pandas中将本地CSV转换为数据帧

在Django中重命名我的表后,旧表中的项目不会被移动或删除

应用指定的规则构建数组

如何在Python中解析特定的文本,这些文本包含了同一行中的所有内容,

Polars时间戳同步延迟计算

有没有一种方法可以在朗肯代理中集成向量嵌入

用0填充没有覆盖范围的垃圾箱

具有不匹配列的2D到3D广播

try 使用RegEx解析由标识多行文本数据的3行头组成的日志(log)文件