【Python】Djangoで個別のページを作成する手順

こんにちは、nishi_talk(@nishi_talk)です。
Pythonで人気のフレームワークDjango(ジャンゴ)に個別ページを作成する方法をご紹介します。




作成したいページ

今回作成するページ名「report(アプリ名)」とします。
追加、編集するファイルはこちらです。

$ tree
.
project
├── project_site
│   ├── settings.py
│   ├── test.py
│   ├── urls.py ←編集する
│   └── wsgi.py
├── manage.py
├── static
├── report(アプリ名)
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── tests.py
│   ├── templates ←追加する
│   │   └── report
│   │       └── post_list.html
│   ├── urls.py ←追加する
│   └── views.py ←編集する
└── uwsgi.ini

全体のURLの作成

まずはこのファイルを編集。

├── project_site
│   ├── urls.py ←編集する

urls.pyの編集した箇所はdjango.urlsのincludeを呼び出し。

from django.contrib import admin
from django.urls import path, include # ←includeの記述を追加

urlpatterns = [
    path('report/', include('report.urls')), # ← ここを追加
    path('admin/', admin.site.urls),
]



個別のURLの作成

個別のテンプレートを呼び出す設定をする。
report/urls.pyを追加して編集します。

・
├── report
│   ├── urls.py ←追加して編集
・
from django.urls import path
from . import views

urlpatterns = [
    path('', views.post_list, name='post_list'),
]

次に、report/views.pyを編集します。

・
├── report
│   ├── views.py ←編集
・
from django.shortcuts import render

# Create your views here.
def post_list(request):
    return render(request, 'report/post_list.html', {})

reportの配下にtemplatesとreportのディレクトリとpost_list.htmlを作成します。

・
├── report
│   ├── templates ←追加する
│   │   └── report
│   │       └── post_list.html
・

post_list.htmlを編集します。

<html>
<body>
    <p>Hi there!</p>
    <p>It works!</p>
</body>
</html>

settings.pyを編集します。

・
・
・
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'report.apps.ReportConfig', ←追記
]
・
・
・

runしているサーバーを再起動します。
reportディレクトにアクセスするとページが表示されます。

http://xxxxxx.com/report/