Web Application: 第10回 HTMLで内容を作成する

前回までで carbikeのindex画面とpredict画面を生成しました。

今回はhtmlを記述していってwebサイトをかっこよくしていきます。

Contents

django-bootstrap4 をインストール

django-bootstrap4を使いますので、

> pip install django-bootstrap4をします。

django-bootstrap4-1.0.1 が入りました。

htmlファイルの作成

/myproject/car_motorbike/ の下に

  • /templates/carbike/base.html
  • /templates/carbike/index.html
  • /templates/carbike/predict.html

というファイルを3つ作成します。

まずはじめに各ページ共通の部分である雛形としてbase.htmlを作成します。

index.htmlとpredict.htmlには各ページ固有の内容を記述して、雛形であるbase.htmlに埋め込んでいくやり方を取ります。

base.html の作成

各ページ共通の部分である雛形です。

bootstrap4の記法は下記のようにDTL: Django Template Languageで

{% xxxxxxx %} と書きます。

1.タイトル

{% block title %}{% endblock %} の部分にindex.html,およびpredict.html各ページ固有のタイトルが代入されます。

2.内容

{% block content%}{% endblock %} の部分にindex.html,およびpredict.html各ページ固有の内容が代入されます。

cssファイルの作成

上記、base.htmlの中で、スタイルシートの宣言をしていますが、自分でディレクトリとファイルを作成する必要があります。

<link rel=’stylesheet’ type=”text/css” href=”{% static ‘carbike/css/style.css’ %}”>

staticディレクトリを myproject/car_motorbike/直下(templatesと同階層に作成して、その中に/carbike/css/style.css というcssファイルを作成しておきます。

あとで記述していきますので、現時点では空ファイルでOKです。

index.html の作成

indexベージを作成します。

1.埋め込み先の宣言

雛形ページであるbase.htmlに対してタイトルと拡張宣言をします。

{% extends ‘carbike/base.html’ %}

2.埋め込むタイトルを定義

{% block title %}xxxx{% endblock %}

3.埋め込む内容を定義

{% block content %}xxxx{% endblock %}

forms.py を作成する

myproject/car_motorbike/の下に forms.pyを新規作成します。

views.py へforms.pyを埋め込む

indexページの表示内容であるindex関数の部分を hello worldをreturnするだけの状態から、formを表示する内容に変更します。

やっていることは3つのみ

1.テンプレートオブジェクトを定義

template = loader.get_template(‘carbike/index.html’)

2.コンテキストオブジェクトを定義

context = {‘form’:PhotoForm()}

3.HttpResponseをreturnする

return HttpResponse(template.render(context, request))

apps.pyを確認する

現在このアプリケーションが認識されているアプリ名を確認します。

CarMotorbikeConfigクラスの中に name = ‘car_motorbike’ と定義されています。

これを 後述のsettings.pyのINSTALLED_APPSリストに追加します。

myproject/settings.py を編集する

# Application definition の部分を書き換えます。

リストINSTALLED_APPS にクラス名’car_mortorbike.apps.CarbikeConfig’と ‘bootstrap4’を追記します。

 

ではここまでをブラウズしてみます。

仮想環境へ conda activate djangoai

開発サーバーへ python manage.py  runserver

url                   http://127.0.0.1:8000/carbike

ここで、画像を選択肢画提出ボタンを押すと、ページが遷移します。

ここはまだ作り込んでいないので、これでOKです。

次回

以上、次回は第11回目です。

django 複雑ですねえ。これは習得するのに時間がかかる・・・。(´・ω・`)