Web制作、Web開発の歩き方

初心者のためのDjango入門

■第3話:DjangoのTemplateとForm機能

(最終更新日:2022.05.28)

Djangoフレームワークのイメージ
この記事は6分で読めます!
(絵が小さい場合はスマホを横に)

「Templateって枯れた技術だよね?」

モダンなWeb開発ではフルスタックフレームワークのTemplate機能を使わず、 フロント(表示)の部分はReactやVueに任せて、APIサーバーとして使うのが現在主流である。 よって、このTemplateは時代遅れの枯れた技術とも言える。しかし、今まで長く使われてきた分、セキュリティ面は非常にしっかりとしている。 (加えてフロントとバックエンドが分かれていないモノリス故のセキュリティの高さもあるが。) Django自体はApacheやNginxといったWebサーバー上で動くため、Node.jsが使えないレガシーな環境でもWeb開発ができる。 技術の幅は広がるはずだ。 今回はこのDjangoのTemplateとFormの機能を学んでいこう。仕組みから学ぶことは多いはずだ。


1.DjangoのTemplate

DjangoのTemplateはデフォルトの設定だと、 作成しているアプリのtemplatesディレクトリ内にhtmlファイルを作成することで、Webページを作ることができる。

まずbase.htmlを作る。これは、全てのページに共通する骨組み部分である。 下記のコードを見てもらえばわかると思う。 ヘッダー等の定型部分をここに書き、{% block content %} {% endblock content %}の部分に各htmlファイルのコンテンツが入る。 {% block header %} {% endblock header %}には、各htmlファイルでヘッダーの文字等を指定できる。 骨組み部分(base.html)に、ユニークな各htmlのコンテンツを差し込むという構成である。

templatesディレクトリの構成とbase.html

次に各コンテンツに当たるhtmlファイルを見てみよう。下記の左はユーザー登録完了後の画面を生成するregistration.htmlになる。 最初にextendsで骨組みとなるbase.htmlを呼び出す。block content、endblock contentに囲まれた部分が差し込むコンテンツになる。 加えて、Viewから送られた変数をこのhtmlテンプレート上で展開できる。一番上に「if user.is_authenticated」とあるが、 Viewから送られたuserが認証されているかどうかを確認している。

このようにif文やfor文、関数を実行する場合は、{% %}で囲み、Template中で処理することができる。 変数を呼び出す場合は右のstore.html中にあるように、{ { store.address } }と言った感じで波括弧で括る。 ここでは、データベースから取り出したstoreテーブルのカラム要素をfor文で展開している。 (正確にはModel→View→Templateの順にバケツリレーしたデータを受け渡して、storeテーブルのデータをstore.htmlに受け渡している。) このようにTemplateでは、Viewから受けとったデータをhtml上に展開することができる。

registration.html(左)とstore.html(右)

2.DjangoのForm機能

次にDjangoのフォーム機能を説明する。下記はDjangoで用いるforms.pyファイルの中身である。 これは、ほとんどModelに相当する機能だと思ってもらっていい。 Form値として入力するfieldを指定している。nameとmailとageだ。データベースTableのフィールドにも相当する。 これを最終的にTemplate上に展開し、ブラウザ上に表示したものが下図になる。

Djangoのforms.pyの例(上)、そのformに対応するHTML(下)

Form入力画面の作成は、通常のMVTと同じ流れをくむ。 forms.pyファイルのhelloform関数中で、モデル(forms.py)からForm値を受け取り、それをテンプレート(helloform.html)に展開している。 すると、上記に既に示したForm入力のHTMLが表示される。form.as_pはPタグで展開しろという命令で、 これをform.as_tableにすれば、Tableで展開することができる。非常にシンプルにForm入力画面を実装できる。

Formのviews.py(左)とhelloform.html(template)(右)

3.まとめ

Djangoを用いると、SQLのCRATE TABLEとデータのINSERT、セキュリティを考慮したフォーム機能までを一貫して少ないコードで、 Pythonだけで作れてしまう。データベース依存を排除し、オブジェクト指向で完結する。この点が非常に優れている。

▼参考図書、サイト

 「Djangoのツボとコツがゼッタイにわかる本」 大橋亮太 秀和システム
 「現場で使えるDjango管理サイトのつくり方」 横瀬明仁
   【Django】お問い合わせフォーム(forms.py)の作成手順・各種入力機能紹介 DXCEL WAVE


Introduction to Django for Beginners ■Episode 3: Django Templates and Forms (Last updated: 2022.05.28) Image of Django framework This article takes about 6 minutes to read! (Rotate your phone sideways if the images are too small.) "Aren't templates outdated tech?" In modern web development, it's common to use Django as an API backend and leave the front-end rendering to frameworks like React or Vue. That makes Django’s template engine seem like outdated technology. However, its long history has made it very secure. Additionally, Django’s monolithic nature (not separating frontend/backend) further contributes to its strong security. Since Django runs on web servers like Apache or Nginx, it's also suitable for legacy environments where Node.js isn't available. This expands your tech possibilities. In this article, we'll dive into Django's Template and Form features. Understanding the mechanics will be beneficial. [Table of Contents] Django Templates Django Forms Summary 1. Django Templates By default, Django templates are created inside the `templates` directory within your app. Start by creating a `base.html` file, which serves as the skeleton for all your pages. In it, common elements like headers go outside the content block, and unique content is inserted between `{% block content %}` and `{% endblock content %}`. You can also define blocks like `{% block header %}` to customize elements like the header in each HTML file. Structure of templates directory and base.html Let’s look at a specific template next. The left side of the image below shows `registration.html`, the page displayed after successful user registration. It begins with `extends` to include `base.html`. The content placed within `{% block content %}` is inserted into the layout. You can also render variables passed from the View in the template. For example, `if user.is_authenticated` checks if the user object passed from the View is authenticated. You can use logic like `if` and `for` with `{% %}` and output variables with `\{\{ variable \}\}`. As shown in `store.html` on the right, this lets you loop through and display items such as a store's address using `\{\{ store.address \}\}`. The data flows from Model → View → Template, like passing a bucket down a line. registration.html (left) and store.html (right) 2. Django Forms Now let’s look at Django's form features. Below is an example of a `forms.py` file, which is conceptually similar to a Model. It defines fields such as `name`, `mail`, and `age` for form input—like columns in a database table. These form fields are later rendered in a template, as shown in the image below. Example of Django's forms.py (top) and the corresponding HTML form (bottom) The process of creating a form input page follows the same MVT (Model-View-Template) flow. The `helloform` function in `forms.py` receives form data, which is then passed to the `helloform.html` template for rendering. As shown above, this results in the browser displaying the form. Using `form.as_p` renders it with paragraph tags, while `form.as_table` renders it in a table. This allows you to easily implement form input screens with minimal code. views.py for Forms (left) and helloform.html (right) 3. Summary With Django, you can handle table creation, data insertion, and secure form handling all using Python with minimal code. It removes dependency on SQL and allows object-oriented development from end to end—one of its biggest strengths. ▼References  "The Essentials and Tips of Django" by Ryota Ohashi (Shuwa System Publishing)  "How to Build a Practical Django Admin Site" by Akihito Yokose    [Django] How to Build Contact Forms (forms.py) and Input Features — DXCEL WAVE