概要
Djangoの学習をしております。
現在、「店」というテーブルを定義しており、その店ごとに毎月の「売上計画」テーブルを持っています。
「店」の詳細ページで、その「店」の「売上計画」の概要をリスト表示し、詳細ボタンをクリックするとその「売上計画」の詳細ページに遷移させようとしています。
URLを、
(1)店の詳細画面: xxx/shop/店名
(2)売上計画の詳細画面 :xxx/shop/店名/売上計画id
というように持たせたいと思い、urls.pyなどを設定しましたが、(1)はうまくできるものの、(2)の売上計画の詳細画面への遷移に、「店名」と「売上計画id」を渡すことが出来ずにエラーになってしまいました。
(2)を「xxx/shop/売上計画id」とすれば出来るの分かるのですが、どうしても階層構造のURL(店の下の階層に計画がある)にしたく、上記のようにしています。
環境
python: 3.7
django: 2.2.x
試したこと
py
1(urls.py) 2from django.urls import path 3 4from . import views 5 6app_name = 'myapp' 7 8urlpatterns = [ 9 path('', views.IndexView.as_view(), name='index'), 10 path('shops/<str:name>', views.ShopDetail.as_view(), name='shop_detail'), 11 path('shops/<str:name>/<int:id>', views.PlanDetail.as_view(), name='plan_detail'), 12]
py
1(views.py) 2from django.conf import settings 3from django.shortcuts import get_object_or_404, render, redirect, resolve_url 4from django.http import HttpResponse 5from django.views import generic 6from django.views.generic import ListView, DetailView, TemplateView 7from .models import Plan, Shop 8 9 10class IndexView(TemplateView): 11 def get(self, request, *args, **kwargs): 12 shop_list = Shop.objects.all() 13 plan_list = Plan.objects.all().order_by('shop', 'month') 14 params = { 15 'shop_list': shop_list, 16 'plan_list': plan_list, 17 } 18 return render(request, 'myapp/index.html', params) 19 20 21 22class ShopDetail(DetailView): 23 model = Shop 24 slug_field = 'name' 25 slug_url_kwarg = 'name' 26 27 def get_context_data(self, *args, **kwargs): 28 plan_list = Plan.objects.filter(shop=kwargs['object']) 29 params = { 30 'plan_list': plan_list, 31 } 32 33 return params 34
html
1(shop_detail.html) 2<!doctype html> 3<html> 4 <head> 5 <meta charset="utf-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 7 <title>WebAPP</title> 8 </head> 9 <body> 10 <div class="container"> 11 <div class="row"> 12 <div class="col"> 13 <h1>SHOP Detail</h1> 14 <p>Shop名</p> 15 <p>{{ object }}</p> 16 {% for item in plan_list %} 17 <p>{{ item.month }}月: <a href="{% url 'myapp:plan_detail' item.shop item.id %}">詳細をみる</a></p> 18 {% endfor %} 19 </div> 20 </div> 21 </div> 22 </body> 23</html>
上記HTMLで詳細を見るボタンをクリックすると、
Generic detail view PlanDetail must be called with either an object pk or a slug in the URLconf.
というエラーが返ってきます。
ご教授いただけると幸いです。
よろしくお願いいたします。

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/07/01 01:31