This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 3 years have passed since last update.

[Day 36]Hello Django!を表示させよう

Last updated at Posted at 2021-02-20

February 20, 2021
←前回:Day 35 自分でweb開発を一から作ってみることにした

「Djangoを一から学びたい」とのことでありましたら[Day 1]Djangoの開発環境から読むことをおすすめします。

はじめに

昨日から自分的にはdjango学習の第二章がはじまった感じです。
今回はwebサイトに自分で表示させたい文字を表示させていこうかと思います。
がんばっていきましょう!

アプリの追加

以下の文ををターミナル上で入力します。

(venv)django_website % python manage.py startapp website

VSCodeで確認するとwebsiteというアプリが追加されているかと思います。
今後はこのアプリを使っていくことになります。

アプリの設定

自分で作ったアプリは自分で設定しなくてはいけません。
要素を追加していきます。

django_website/settings.py(一部抜粋)
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の中身を追加してきます。

templates/index.html
<h1>Hello Django!</h1>

正直、中身はなんでもいいです。
好きなものを書いましょう。

Viewの設定

viewを追加していきます。

website/view.py
from django.views.generic import TemplateView

class IndexView(TemplateView):
    template_name = 'index.html'

ここでは、先ほど作成したindex.htmlをweb上に表示させるためのクラスを作成します。TemplateViewをインポートします。

urlの設定

urlも設定していきます。

website/urls.py
from django.urls import path
from .views import IndexView

urlpatterns = [
    path('', IndexView.as_view()),
]
django_website/urls.py
from django.contrib import admin
+ from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
+   path('', include('website.urls')),
]

完成!

このように表示されていれば完成です。
スクリーンショット 2021-02-19 11.13.22.png

ここまでを解説します。
まず、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サイトを作成する

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