[Django初心者向け] Djangoで新しいページを作る手順をまとめました

Djangoに限らずWebフレームワークにはURLのルーティングが簡単にできる仕組みがあります。本記事ではDjangoでのルーティングを設定し、ブラウザで `localhost:8000`にアクセスした時にHello Worldを表示させるやり方をまとめました。

[既存ファイルの修正] urls.py

diff --git a/あなたのアプリ名/urls.py b/あなたのアプリ名/urls.py
index 012ebae..bda590f 100644
--- a/あなたのアプリ名/urls.py
+++ b/あなたのアプリ名/urls.py
@@ -14,8 +14,9 @@ Including another URLconf
     2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
 """
 from django.contrib import admin
-from django.urls import path
+from django.urls import path, include
 urlpatterns = [
     path('admin/', admin.site.urls),
+    path('', include('sample.urls')),
 ]

ここでは `sample/urls.py`を読み込むように設定しているので次は実際にファイルを作っていきます。

[新規ファイル作成] sample/urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('', views.index, name='index'),
]

このファイルの indexは、次のファイルの `def index`に対応している

[新規ファイル作成] sample/views.py

from django.shortcuts import render
def index(request):
    return render(request, 'sample/index.html', {})

この indexに入ってくる処理はこのテンプレートを見ますよって感じです。

[新規ファイル作成] sample/templates/sample/index.html

Hello World

さて、ここまでくればあともうちょっとです。

[既存ファイル修正] settings.py

 TEMPLATES = [
     {
         'BACKEND': 'django.template.backends.django.DjangoTemplates',
-        'DIRS': [],
+        'DIRS': [
+            os.path.join('sample', 'templates'),
+        ],
         'APP_DIRS': True,
         'OPTIONS': {
             'context_processors': [

ブラウザでアクセスしてみよう

さて、これで準備は万端、、、ではないんです。新しくルーティングを設定した時はサーバ再起動が必要なので `python manage.py runserver` を実行してから `localhost:8000`にアクセスしてみてください。

最後までお読みいただきありがとうございました!

Related Posts