3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

urls.pyの振り分け例と呼び出される関数の引数について

Posted at

はじめに

Django2.0以降のURLconf(urls.py)に関して、公式ドキュメントでまだ翻訳されていない箇所を読んで調べた内容を簡単にまとめます(公式ドキュメントの翻訳記事というわけではありません)。

urls.pyでの振り分け例

from django.urls import path

from . import views

urlpatterns = [
    path('articles/2003/', views.special_case_2003),
    path('articles/<int:year>/', views.year_archive),
    path('articles/<int:year>/<int:month>/', views.month_archive),
]
  • /articles/2005/03/というURLの場合、3番目の'articles/<int:year>/<int:month>/'にマッチします。

  • /articles/2003/というURLの場合、2番目の'articles/<int:year>/'ではなく、1番目の'articles/2003/'にマッチします。Djangoは、urlpatternsを順に調べて最初にマッチしたパターンの関数を呼び出すためです。

  • /articles/2003というURLの場合、最後に/が無いため、どのパターンにもマッチしません。

urls.pyで呼び出す関数の引数について

  • 第一引数にはHttpRequestオブジェクトのインスタンスが渡されます。

  • <int:year>などのパスコンバータが使用されている場合、その部分がキーワード引数となります。

from django.urls import path

from . import views

urlpatterns = [
    path('articles/<int:year>/<int:month>/', views.month_archive),
]

例えば、/articles/2005/03/というURLの場合、Djangoはviews.month_archive(request, year=2005, month=3)を呼び出します。

urls.pyとGETのパラメータ

urls.pyでの振り分けでは、GETのパラメータを考慮した記述は不要です。

from django.urls import path

from . import views

urlpatterns = [
    path('books/', views.BookListView.as_view()),
]

例えば、/books/?page=3へのリクエストは、上記の'books/'にマッチしてくれます。

参考

Django2.1公式ドキュメント URLディスパッチャ

3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?