February 20, 2021
←前回:Day 35 自分でweb開発を一から作ってみることにした
「Djangoを一から学びたい」とのことでありましたら[Day 1]Djangoの開発環境から読むことをおすすめします。
はじめに
昨日から自分的にはdjango学習の第二章がはじまった感じです。
今回はwebサイトに自分で表示させたい文字を表示させていこうかと思います。
がんばっていきましょう!
アプリの追加
以下の文ををターミナル上で入力します。
(venv)django_website % python manage.py startapp website
VSCodeで確認するとwebsiteというアプリが追加されているかと思います。
今後はこのアプリを使っていくことになります。
アプリの設定
自分で作ったアプリは自分で設定しなくてはいけません。
要素を追加していきます。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
+ 'website',
]
テンプレートの作成
テンプレートフォルダを作成していきます。
いろんなやり方がありますが、筆者はVSCodeで右クリックして作成するのを好むのでそのやり方で行います。
先ほど作ったアプリ内にtemplatesフォルダを作成します。
で、その中にindex.htmlというファイルを作成します。
仮にターミナル上でやるとするならば、
% cd website
% mkdir templates
% cd templates
% emacs index.html
たぶんこれでできるかと思います。
index.htmlの中身を追加してきます。
<h1>Hello Django!</h1>
正直、中身はなんでもいいです。
好きなものを書いましょう。
Viewの設定
viewを追加していきます。
from django.views.generic import TemplateView
class IndexView(TemplateView):
template_name = 'index.html'
ここでは、先ほど作成したindex.htmlをweb上に表示させるためのクラスを作成します。TemplateViewをインポートします。
urlの設定
urlも設定していきます。
from django.urls import path
from .views import IndexView
urlpatterns = [
path('', IndexView.as_view()),
]
from django.contrib import admin
+ from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
+ path('', include('website.urls')),
]
完成!
ここまでを解説します。
まず、django_website/urls.pyからトップページのときwebsite.urlsをインクルードしなさいと、命令がでます。
次に、website/urls.pyではトップページのときIndexViewに行きなさいと、命令がでます。
で、views.py内のIndexViewクラスではindex.htmlを返しています。
最後に、index.html内に書いてある内容がWebサイトに表示されることになります。
おわりに
一通りDjangoがどのようなものかわかってきたので、今後は自分で解説しながら進めていくことにします。
進むスピードは遅くなるかもしれませんが、ためになるとは思うので続けていきます。
それではまたまた
←前回:Day 34 タイムゾーンと日時オブジェクトを扱う
→次回:Day 37 Djangoで移動できるWebサイトを作成する