LoginSignup
1
0

More than 1 year has passed since last update.

Djangoで複数のパスパラメータを含むURLを実装する

Posted at

目的

以下のように、パスパラメータを複数含むURLを、Djangoで定義・実装する方法の整理
http://localhost/<プロジェクトID>/<タスクID>/

参考:公式チュートリアル

URL定義

たとえば、複数のプロジェクトが、複数のタスクを持つ、そんなアプリがあったとする。
タスク詳細を表示するURLは複数の変数(パスパラメータ)を持つ。
このような場合、Djangoでは以下のようにURLを定義できる。

config.urls.py
urlpatterns = [
    path('', views.projects),
    path('<int:pj_id>/', views.detailProject),
    path('<int:pj_id>/<int:tk_id>', views.detailTask)
]

この定義では、以下のURLにアクセスできる。

  • http://localhost/ : プロジェクト一覧
  • http://localhost/pj_id/ : プロジェクト詳細
  • http://localhost/pj_id/tk_id/ : タスク詳細

View実装

Viewは以下のように実装できる。

views.py
def projects(request):
    return HttpResponse("<html><body>プロジェクト一覧</body></html>")
def detailProject(request, pj_id):
    return HttpResponse(f"<html><body>{pj_id}</body></html>")
def detailTask(request, pj_id, tk_id):
    return HttpResponse(f"<html><body>{pj_id}, {tk_id}</body></html>")

ポイント

  • Viewの引数名(pj_id, tk_id)は、urlsに定義したパスパラメータの名称と一致させる必要がある。
  • 順序は、パスパラメータの順序と異なってもよい。

余談

プロジェクト部分とタスク部分を別アプリとして作って、urlsを分けることも可能。
これでも、detailTaskには、pj_idとtk_idが渡される。

config.urls.py
urlpatterns = [
    path('', include('projects.urls'))
]
projects.urls.py
urlpatterns = [
    path('', views.projects),
    path('<int:pj_id>/', views.detailProject),
    path('<int:pj_id>/', include('tasks.urls'))
]
tasks.urls.py
urlpatterns = [
    path('<int:tk_id>/', views.detailTask)
]
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0