はじめに
この講座を見てDjangoの勉強をしています。
今後の開発のために簡潔に開発の流れをまとめました。
その2です
開発環境構築の流れ(続き)
アプリケーションを作成する(前記事にも書いてあります)
$ python manage.py startapp sample_app
sample_projectフォルダ内のsettings.pyを修正する
40行目ぐらい
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
+ "sample_app",
]
sample_appがアプリケーションとして読み込まれるようにする記述。
sample_projectフォルダ内のurls.pyを修正する
- from django.urls import path
+ from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
+ path("sample_app/", include("sample_app.urls")),
]
http://127.0.0.1:8000/の次がsample_appなら、sample_appフォルダ内のurlsファイルを読み込むようにする記述。
sample_appにurls.pyファイルを新規作成する
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
urlのsample_app/の次が''(何もなし)またはindexならば、viewsファイルのindex関数を読み込むようにする記述。
sample_appフォルダ内のviews.pyを修正する
from django.shortcuts import render
+ from django.http import HttpResponse
# Create your views here.
+ def index(request):
+ return HttpResponse(f'<h1>Hello</h1>')
関数が読み込まれたときに<h1>hello</h1>と返すようにする記述
実行確認
$ python manage.py runserver
urlの末尾にsample_appと追加して実行。Helloと表示されればおk
htmlファイルを返す場合
新規アプリケーションフォルダを作成する
$ python manage.py startapp sample_appapp
sample_appappフォルダとする
sample_project内のsettings.pyを修正する
40行目くらい
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"sample_app",
+ "sample_appapp",
]
sample_appappフォルダ直下にtemplatesフォルダを作成する
templatesという名前じゃないとだめです
templatesフォルダの直下にappappフォルダを作成、さらにその直下にindex.htmlを作成する
<h1>読み込めた</h1>
sample_app内のviews.pyを修正する
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
- return HttpResponse(f'<h1>hello</h1>')
+ return render(request, 'appapp/index.html')
自動でtemplatesフォルダを認識して読み込んでくれるので、templatesの指定は不要。
これでindex関数が実行されたときにHTMLファイルを返すようになった。
実行確認
$ python manage.py runserver
urlの末尾にsample_appと追加して実行。「読み込めた」と表示されればおk
続き