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 37]Djangoで移動できるWebサイトを作成する

Last updated at Posted at 2021-02-21

February 19, 2021
←前回:Day 36 Hello Django!を表示させよう

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

はじめに

今回は移動できるWebサイトを作成していきます。
クリックすると指定のページにアクセスでき、戻ってこれるものを作ります。

今回は新しいプロジェクトを作ります。名前は「django_webiste02」にします。
前回と同様に、自分でアプリを作って、その中にtemplatesフォルダを作成して、htmlファイルを作成していきます。

ここまでの流れは前回行ったのでわからなければ復習してください。
待ってます。

あと、これはどっちでもいいのですが、筆者はエラーを確認しながら作業を進めていくのが好きなので、サーバも一緒に立ち上げます。setting.pyで前回のものを行います。
ドメインの許可とアプリの追加です。

HTML作成

ここではindex.htmlとabout.htmlを作成していきます。
ページを二つ作るということです。

templates/index.html
<!doctype HTML>
<html>
    <head>

    </head>
    <body>
      <h1>ホーム</h1>
    </body>
</html>
templates/about.html
<!doctype HTML>
<html>
    <head>

    </head>
    <body>
      <h1>自己紹介</h1>
    </body>
</html>

Viewの変更

viewを書き換えます。

website/view.py

from django.views.generic import TemplateView

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

class AboutView(TemplateView):
  template_name = 'about.html'urls.py

urlの設定

website/urls.py

from django.contrib import admin
from django.urls import path

from .views import IndexView, AboutView

urlpatterns = [
    path('', IndexView.as_view()),
    path('about/', AboutView.as_view()),
]
django_website02/urls.py(一部抜粋)

from django.contrib import admin
from django.urls import path, include

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

ページを移動できるようにする

templates/index.html(一部抜粋)
    <body>
      <div class='navber'>
        <a href="/">トップ</a>
        <a href="/about">自己紹介</a>
      </div>
      <h1>ホーム</h1>
    </body>

about.htmlも同様なのですが、これだとただのhtmlで効率が悪いです。(後々わかります)
なので、今作成した箇所をパーツ化します。
templatesに_navber.htmlを作成します。

_navber.html
<div class='navber'>
  <a href="/">トップ</a>
  <a href="/about">私たちについて</a>
</div>

で、indexとaboutの方も変更していきます。

index.html(一部抜粋)
    <body>
      {% include '_navber.html' %}
      <h1>ホーム</h1>
    </body>

{% タグ名 %}にすることによりコードをシンプルにできます。

完成!

スクリーンショット 2021-02-20 10.59.34.png

スクリーンショット 2021-02-20 10.59.57.png

このようになっているかと思います。
これで移動できるWebサイトが完成しました。

おわりに

Qiitaに書きながらだとかなり進みが遅くなります。
これだけで1時間半かかりました。
今後は対策を考えながら進めていきます。

それではまたまた

←前回:Day 36 Hello Django!を表示させよう
→次回:Day 38 毎日続けるために方針を変えました

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