Web制作、Web開発の歩き方

初心者のためのDjango入門

■第4話:本番環境におけるDjangoの設定と構成

(最終更新日:2023.04.11)

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

「設定ってどこで変更するの?」

Djangoを使う時、基本操作と同じくらい大事なのが設定ファイルの使い方だ。 Djangoの設定はsetting.pyに書く。ここでは、本番環境でのsetting.pyの設定とDjangoの構成について説明する。


1.本番環境におけるDjangoの設定(setting.py)

Djangoの設定ファイル(setting.py)は、プロジェクトと同名のアプリケーションディレクトリ内にある。 このファイルを開くと、いくつかの設定項目が表示される。 最初に変更が必要なのがDEBUG(下記左)で、デフォルトではDEBUGの表示はTrueになっている。 開発環境ではDEBUGを表示しても問題ないが、本番環境で表示するとエラー発生時に不要な情報がユーザーに漏れることがある。 本番環境にデプロイする際は、DEBUGをFalseにすることを忘れないようにしよう。

ALLOWED_HOSTSは、公開を許可するドメインを指定する場所だ。 テスト環境ではlocalhostを、本番環境では使用しているドメインを指定しよう。 さらに、その下にあるアプリケーションの部分では、現在使用しているアプリケーションを宣言する。 新しいアプリケーションを作成したり、Django REST Frameworkのようなインストール済みアプリを追加したりする場合は、必ず記述しよう。

Middleware(下記右)は、リクエストが送信されたり、レスポンスが返されたりする際に実行される処理だ。 最初はあまり触らないでおくのが良いだろう。 慣れてくると自作のミドルウェアを作る人もいるが、今の段階ではただ存在を認識しておけば十分だ。 また、その下のROOT_URLCONFはデフォルトの設定で問題ない。 指定されたディレクトリのurls.pyが読み込まれ、ルーティングが行われる仕組みになっている。

TEMPLATESは、変更することがよくある設定のひとつだ。 デフォルトでは、各アプリケーションディレクトリにtemplatesディレクトリを配置し、HTMLを表示する仕組みになっている。 ただ、この方法だとTemplateファイル(HTML)が各ディレクトリに散らばってしまうことがある。 Templateファイルを一箇所にまとめたい場合は、BASE_DIR(一番上のディレクトリ直下)にtemplatesディレクトリを設置し、 その場所を指定することができる。下記右下のDIRSでその設定が記述されている。

setting.pyで表示される情報の抜粋(デバッグ、テンプレートディレクトリの設定など)

さらに設定を見ていくと、下記左にデータベースの設定がある。 デフォルトではsqliteが設定されているが、本番環境でよく使われるMySQL(MariaDB)やPostgreSQLに変更することも可能だ。 下記の例ではMySQLの設定が示されており、ユーザー名、パスワード、ポートなどを設定して接続することができる。

さらにその下には言語コードとタイムゾーンの設定がある。 日本で利用する場合は、デフォルトのen-usをjaに、UTCをAsia/Tokyoに変更しよう。

続いて、staticディレクトリ(静的ファイルの置き場所)の設定がある。 これは、画像ファイルやCSS、JavaScriptファイルを置く場所の設定だ。 これもTEMPLATESディレクトリと同様に、BASE_DIR(一番上のディレクトリ直下)に設定することが一般的だ。

さらに、URLの末尾にスラッシュを付ける設定やユーザー認証(ログイン)に関する設定があるが、今回は存在についてのみ触れる。 最後に、サインアップや問い合わせ時にユーザーや管理者に送るメールの設定について説明する。 開発環境の場合は、EMAIL_BACKENDをコンソールに出力するように設定(コメントアウトしてある方)する。 本番環境ではSMTPを選択し、配信元となるメールサーバーのホストURLやポート、メールアドレス、パスワードを設定する項目が存在する。

setting.pyで表示される情報の抜粋(DB、timezone、各種ディレクトリ位置、メール送信の設定)

2.本番環境におけるDjangoの構成

第1話ではDjangoの全体像について解説した。 今回はこれまでの復習も兼ねて、Webサーバーを含めた構成図を紹介する。 下図はDjangoとWebサーバーを示すもので、右側のDjangoの仕組み部分(middlewareより右側)は、 1話~3話を読んでいれば理解できるはずだ。

ここで、左側のWebサーバーとの連携について話をしよう。 開発時はWebサーバーを使用せず、代わりにDjango内蔵のmanage.pyをrunserverさせることで、 ブラウザ上で表示が可能になる(manage.pyが「Webサーバー+wsgi.py」に代わり、簡易サーバーの役割を果たす)。 ただし、manage.pyは並列処理やプロセスの自動再起動ができないため、アクセスが多い本番環境には向かない。

本番環境では、ApacheやNginxと連携(デプロイ)して運用することになる。 デプロイの詳細は技術書や別のサイトに譲るが、要点としては、 wsgiというインターフェースがApache(Webサーバー)とDjango(アプリケーションサーバー)の仲介をしている。 つまり、wsgiと連携できるWebサーバーであれば、Djangoはデプロイできるということだ。 ちなみに、wsgiはPython共通のインターフェースであり、wsgiが使えれば、Flaskなどの別のPythonウェブフレームワークも利用できることを意味する。

最後に、これまで触れていなかったadmin.pyについて説明しよう。 これは非常にシンプルなものだ。Djangoデフォルトの管理ページで管理するかどうかを設定するファイルである。 admin.pyに「admin.site.register(モデル名)」を追記することで、管理サイトで管理できるModel(データベースのテーブル)を増やすことができる。これにより、管理画面からデータの追加や編集が容易になる。

Djangoの構成図


▼参考図書、サイト

 「Djangoのツボとコツがゼッタイにわかる本」 大橋亮太 秀和システム
 「現場で使えるDjango管理サイトのつくり方」 横瀬明仁
   言語を日本語に切り替える方法【settingsファイルで一発です】 Code for Django
   WEBサーバのinterfaceのイメージはこんな感じだろうか〜CGI, FastCGI, Apacheモジュール, WSGI〜 Blow Up by Black Swan
   djangoは誰が動かしているのか?(デプロイのための俯瞰) Qiita


Introduction to Django for Beginners ■Episode 4: Django Settings and Structure for Production Environment (Last updated: 2023.04.11) Image of Django framework This article takes 6 minutes to read! (Rotate your smartphone for a larger image) "Where do I change the settings?" When using Django, knowing how to work with the settings file is just as important as understanding the basic operations. Django settings are written in the `settings.py` file. This article explains how to configure `settings.py` and Django's overall structure for a production environment. [Table of Contents] Django Settings for Production (settings.py) Django Structure in Production Environment 1. Django Settings for Production (settings.py) The settings file (`settings.py`) is located in the project directory with the same name. When you open this file, you will see several configuration options. One of the first items to change is `DEBUG`. By default, it is set to `True`. While this is fine for development, leaving it enabled in production can expose unnecessary information to users during an error. Always set `DEBUG = False` when deploying to production. The `ALLOWED_HOSTS` setting defines the domains that are allowed to access your site. Use `localhost` for test environments and your actual domain in production. Below that is the list of installed applications. Whenever you create a new app or add a third-party app like Django REST Framework, be sure to add it here. `Middleware` is a list of processes that run during request/response handling. It's best not to touch this when you're just starting out. As you become more experienced, you might create your own middleware, but for now, just know it exists. `ROOT_URLCONF` usually doesn’t need to be changed. It tells Django where to look for `urls.py` to handle routing. `TEMPLATES` is a commonly edited setting. By default, templates are stored in each app's `templates` folder. If you'd prefer to keep all templates in one central place, you can create a `templates` directory directly under `BASE_DIR` and set it in the `DIRS` section. Sample `settings.py` content (debug mode, template directory setup, etc.) Further down in the file, you'll find the database settings. By default, Django uses SQLite, but you can change it to use MySQL (MariaDB) or PostgreSQL, which are commonly used in production. In the example below, the MySQL configuration includes username, password, port, and other details for connecting. Then there's the language and time zone settings. If you're in Japan, change the language from `en-us` to `ja` and the time zone from `UTC` to `Asia/Tokyo`. Next is the `static` directory setting, which defines where static files like images, CSS, and JavaScript are stored. Like templates, it is common to place the `static` folder under `BASE_DIR`. Other settings include trailing slashes for URLs and user authentication (login), which we’ll briefly mention here. Finally, there's the email configuration used to send messages during signup or contact form submissions. In development, you can set `EMAIL_BACKEND` to output emails to the console (this is usually commented out). In production, use SMTP and configure the host, port, email address, and password of your mail server. Sample `settings.py` content (database, timezone, directory paths, email configuration) 2. Django Structure in Production Environment In Episode 1, we explained Django’s overall structure. Here, as a recap, we’ll introduce a diagram that includes the web server configuration. The right side of the diagram shows Django’s internal components (from middleware onward), which you should understand if you’ve read Episodes 1 to 3. Let’s now look at the left side—the web server integration. During development, you usually don’t use a web server. Instead, you use Django’s built-in `manage.py runserver` command, which runs a lightweight server for displaying the site in a browser. However, `manage.py` does not support parallel processing or automatic process restarting, making it unsuitable for production environments. In production, Django is deployed alongside web servers like Apache or Nginx. While the technical setup is beyond this article, the key point is that a Python interface called `wsgi` connects the web server to Django. In other words, as long as a web server supports `wsgi`, Django can be deployed with it. Note that `wsgi` is a common Python interface, so other frameworks like Flask can also be deployed using it. Lastly, let’s briefly discuss `admin.py`, which we haven't covered before. This file controls what is shown in Django’s admin panel. By adding `admin.site.register(ModelName)` to `admin.py`, you can make a model (i.e., a database table) manageable via the admin site. This makes it easy to add or edit data from the web interface. Django system architecture ▼References  “Django no Tsubo to Kotsu ga Zettai ni Wakaru Hon” by Ryota Ohashi, Shuwa System (Japanese book)  “Genba de Tsukaeru Django Kanri Site no Tsukurikata” by Akihito Yokose (Japanese book)    How to Change Language to Japanese (via settings file) – Code for Django    Overview of Web Server Interfaces: CGI, FastCGI, Apache Modules, WSGI – Blow Up by Black Swan    Who Runs Django? (Deployment Overview) – Qiita