如何将Django URL参数传递给模板的URL方法?

1 投票
2 回答
42 浏览
提问于 2025-04-14 17:48

我有一个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
    })

这是我的region-service-cost.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

2 个回答

0

如果你想让浏览器指向这个地址:

http://127.0.0.1:8000/region_service_cost/global/

在 region-service-cost.html 文件中:

<a href="{% url 'region-service_cost' 'global' %}">Region Service Cost</a>
1

把你的 views.py 文件里的 region_service_cost() 函数换成下面这个:

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

你代码的问题在于没有把地区信息传递到你的 HTML 页面,所以在这一行中,HTML 页面不知道 region 是什么意思:

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

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

撰写回答