From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../django/development_environment/index.html | 433 +++++++++++++++++++ files/ja/learn/server-side/django/index.html | 69 +++ .../server-side/django/introduction/index.html | 281 +++++++++++++ .../ja/learn/server-side/django/models/index.html | 461 +++++++++++++++++++++ .../server-side/django/skeleton_website/index.html | 398 ++++++++++++++++++ .../tutorial_local_library_website/index.html | 99 +++++ .../django/web_application_security/index.html | 180 ++++++++ 7 files changed, 1921 insertions(+) create mode 100644 files/ja/learn/server-side/django/development_environment/index.html create mode 100644 files/ja/learn/server-side/django/index.html create mode 100644 files/ja/learn/server-side/django/introduction/index.html create mode 100644 files/ja/learn/server-side/django/models/index.html create mode 100644 files/ja/learn/server-side/django/skeleton_website/index.html create mode 100644 files/ja/learn/server-side/django/tutorial_local_library_website/index.html create mode 100644 files/ja/learn/server-side/django/web_application_security/index.html (limited to 'files/ja/learn/server-side/django') diff --git a/files/ja/learn/server-side/django/development_environment/index.html b/files/ja/learn/server-side/django/development_environment/index.html new file mode 100644 index 0000000000..ac824323ea --- /dev/null +++ b/files/ja/learn/server-side/django/development_environment/index.html @@ -0,0 +1,433 @@ +--- +title: Django 開発環境の設定 +slug: Learn/Server-side/Django/development_environment +tags: + - Python + - Webフレームワーク + - django + - サーバーサイドプログラミング +translation_of: Learn/Server-side/Django/development_environment +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/Introduction", "Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django")}}
+ +

Djangoがどういうものか知ったので、Windows、Linux(Ubuntu)、およびmacOSでDjango開発環境をセットアップしてテストする方法を説明します。一般的なオペレーティングシステムを使っていれば、Djangoアプリケーションの開発を始められます。

+ + + + + + + + + + + + +
前提条件:ターミナル/コマンドラインを開く方法を知っていること。開発用コンピュータのオペレーティングシステムにソフトウェアパッケージをインストールする方法を知っていること。
目的:あなたのコンピュータでDjango(2.0)の開発環境を動かします。
+ +

Django開発環境の概要

+ +

Djangoは自分のコンピュータをセットアップするのはとても簡単で、Webアプリケーションの開発を開始できます。このセクションでは、開発環境の内容を説明し、セットアップおよび構成オプションの一部の概要を示します。また、Ubuntu、macOS X、WindowsにDjango開発環境をインストールする際の推奨される方法と、そのテスト方法について説明します。

+ +

Django開発環境とは何ですか?

+ +

開発環境はDjangoをローカルコンピュータにインストールしたものです。Djangoアプリを開発し、運用環境にデプロイする前にテストできます。

+ +

Django自体が提供する主なツールは、Djangoプロジェクトを作成して作業するためのPythonスクリプトと、ローカルの(つまり、外部のWebサーバーではなく)Django Webアプリケーションをあなたのコンピュータ上のウェブブラウザでテストするための簡単な開発用Webサーバーです。

+ +

開発環境の一部を構成する他の周辺ツールがありますが、ここではカバーしません。これには、コードを編集するためのテキストエディタやIDE、コードの異なるバージョンを安全に管理するためのGitのようなソース管理ツールなどがあります。すでにテキストエディタがインストールされていると仮定しています。

+ +

Djangoの構成オプションとは?

+ +

Djangoは、インストール場所と設定の方法に関して非常に柔軟性があります。Djangoは次のようなことが可能です:

+ + + +

これらのオプションは、それぞれわずかに異なる構成とセットアップを必要とします。以下のサブセクションでは、いくつかの選択肢について説明します。この記事の残りの部分では、いくつかオペレーティングシステムにDjangoをセットアップする方法を説明します。このモジュールの残りの部分は、セットアップが済んでいる想定です。

+ +
+

ノート: その他のインストールオプションについては、Djangoの公式ドキュメントでカバーされています。下記で適切なドキュメントにリンクしています。

+
+ +

どのオペレーティングシステムがサポートされていますか?

+ +

DjangoのWebアプリケーションは、Python 3プログラミング言語を実行できるほとんどすべてのマシン(Windows、MacOS X、Linux / Unix、Solarisなど)で実行できます。ほとんどのコンピュータで開発中にDjangoを実行できるパフォーマンスが必要です。

+ +

この記事では、Windows、macOS X、およびLinux/Unixについて説明します。

+ +

どのバージョンのPythonを使うべきですか?

+ +

最新のバージョンを使用することをお勧めします - 執筆時点ではPython 3.6です。

+ +

必要であればPython 3.4以上を使用できます(Python 3.4のサポートは将来のリリースでは廃止される予定です)。

+ +
+

ノート: Python 2.7はDjango 2.0では使用できません(Django 1.11.x系はPython 2.7をサポートする最後のバージョンです)。

+
+ +

どこでDjangoをダウンロードできますか?

+ +

Djangoをダウンロードする場所は3つあります:

+ + + +

この記事ではPyPiからDjangoをインストールし、最新の安定版を入手する方法を説明します。

+ +

どのデータベースですか?

+ +

Djangoは4つの主要なデータベース(PostgreSQL、MySQL、Oracle、SQLite)をサポートしています。また、他の一般的なSQLデータベースやNOSQLデータベースにさまざまなレベルのサポートを提供するコミュニティライブラリもあります。 DjangoはObject-Relational Mapper(ORM)を使用して多くのデータベースの違いを抽象化していますが、回避する方が良い潜在的な問題がまだあります。

+ +

この記事(とこのモジュールのほとんど)では、データをファイルに保存するSQLiteデータベースを使用します。 SQLiteは軽量データベースとしての使用を目的としており、高度な並行性はサポートできません。 ただし、主に読み取り専用のアプリケーションには最適です。

+ +
+

ノート: Djangoは、標準ツール(django-admin)を使用してWebサイトプロジェクトを開始するときに、デフォルトでSQLiteを使用するように設定されています。 これは、追加の設定やセットアップが不要なため、入門には最適な選択です。

+
+ +

システム全体またはPythonの仮想環境にインストールするには?

+ +

Python3をインストールすると、すべてのPython3コードで共有される単一のグローバル環境が得られます。 環境に好きなPythonパッケージをインストールすることはできますが、一度に1つのパッケージしかインストールできません。

+ +
+

ノート: グローバル環境にインストールされたPythonアプリケーションは、お互いに衝突する可能性があります(例えば、同じパッケージの異なるバージョンに依存する場合)。 

+
+ +

Djangoをデフォルト/グローバル環境にインストールすると、コンピュータ上でDjangoの1つのバージョンのみを対象にできます。 古いバージョンに依存しているWebサイトを維持しながら、新しいWebサイト(Djangoの最新バージョンを使用)を作成したい場合、これは問題になる可能性があります。

+ +

その結果、経験豊富なPython/Django開発者は通常、独立したPython仮想環境内でPythonアプリケーションを実行します。これにより、1台のコンピュータ上で複数の異なるDjango環境を使用することができます。Djangoの開発チームは、Pythonの仮想環境を使用することをお勧めしています。

+ +

このモジュールは以下に示す方法で、仮想環境にDjangoをインストールすることを前提としています。

+ +

Python 3のインストール

+ +

Djangoを使用するには、オペレーティングシステムにPythonをインストールする必要があります。Python 3を使用している場合は、Djangoとその他のPythonアプリケーションで使用されるPythonパッケージ/ライブラリの管理(インストール、更新、削除)に使用する Python Package Indexツール『pip3』も必要です。

+ +

このセクションでは、Ubuntu Linux 16.04、macOS X、およびWindows 10のPythonのバージョンを確認し、必要に応じて新しいバージョンをインストールする方法を簡単に説明します。

+ +
+

ノート: 使用しているプラットフォームによっては、オペレーティングシステム独自のパッケージマネージャやその他のメカニズムを使ってPython/pipをインストールできます。ほとんどのプラットフォームでは、 https://www.python.org/downloads/ から必要なインストールファイルをダウンロードし、適切なプラットフォーム固有の方法を使用してインストールできます。

+
+ +

Ubuntu 16.04

+ +

Ubuntu Linux 16.04 LTSにはデフォルトでPython 3.5.2が含まれています。 これを確認するには、bash端末で次のコマンドを実行します:

+ +
python3 -V
+ Python 3.5.2
+ +

しかし、Python 3(Djangoを含む)用のパッケージをインストールするために必要なPython Package Indexツールは、デフォルトでは利用できません。 次のコマンドを使用してbash端末にpip3をインストールできます:

+ +
sudo apt-get install python3-pip
+
+ +

macOS X

+ +

macOS X "El Capitan"やその他の最近のバージョンにはPython 3は含まれていません。これはbash端末で次のコマンドを実行することで確認できます:

+ +
python3 -V
+ -bash: python3: command not found
+ +

python.orgのPython 3(pip3ツールと一緒に)を簡単にインストールできます:

+ +
    +
  1. 必要なインストーラをダウンロードします: +
      +
    1. https://www.python.org/downloads/ を開きます
    2. +
    3. Download Python 3.6.4 ボタンを選択します(正確なマイナーバージョン番号は異なる場合があります)。
    4. +
    +
  2. +
  3. Finderを使用してファイルを探し、パッケージファイルをダブルクリックします。インストールの後、プロンプトが表示されます。
  4. +
+ +

以下に示すように、Python 3を確認することで、正常にインストールされたことを確認できます:

+ +
python3 -V
+ Python 3.6.4
+
+ +

同様にpip3がインストールされていることを確認するには、利用可能なパッケージを一覧表示します:

+ +
pip3 list
+ +

Windows 10

+ +

WindowsにはデフォルトでPythonは含まれていませんが、python.orgからpip3ツールと一緒に簡単にインストールできます:

+ +
    +
  1. 必要なインストーラをダウンロードします: +
      +
    1. https://www.python.org/downloads/ を開きます
    2. +
    3. Download Python 3.6.4 ボタンを選択します(正確なマイナーバージョン番号は異なる場合があります)。
    4. +
    +
  2. +
  3. ダウンロードしたファイルをダブルクリックし、インストールのプロンプトに従ってPythonをインストールします。
  4. +
+ +

Python 3がインストールされたことを確認するには、コマンドプロンプトに次のテキストを入力します:

+ +
py -3 -V
+ Python 3.6.4
+
+ +

Windowsインストーラには、デフォルトでpip3(Pythonパッケージマネージャ)が組み込まれています。次に示すようにインストールされたパッケージを一覧表示できます:

+ +
pip3 list
+
+ +
+

ノート: インストーラは、上記のコマンドが動作するために必要なものすべてをセットアップする必要があります。Pythonが見つからないというメッセージが表示された場合は、システムパスに追加する必要があります。

+
+ +

Python仮想環境内でのDjangoの使用

+ +

仮想環境を作成するために使用するライブラリは、 virtualenvwrapper (LinuxとmacOS X)とvirtualenvwrapper-win(Windows)です。これらはどちらもvirtualenvツールを使用します。ラッパーツールは、すべてのプラットフォーム上のインターフェイスを管理するための一貫したインターフェイスを作成します。

+ +

仮想環境ソフトウェアのインストール

+ +

Ubuntu仮想環境のセットアップ

+ +

Pythonとpipをインストールした後、virtualenvwrapper(virtualenvを含む)をインストールできます。公式インストールガイドはこちら、または下記の手順に従ってください。

+ +

pip3を使用してツールをインストールします:

+ +
sudo pip3 install virtualenvwrapper
+ +

次に、シェルのスタートアップファイルの最後に次の行を追加します(これはホームディレクトリ内の .bashrc という名前の隠しファイルです)。これらは、仮想環境の存在場所、開発プロジェクトディレクトリの場所、およびこのパッケージと共にインストールされるスクリプトの場所を設定します:

+ +
export WORKON_HOME=$HOME/.virtualenvs
+export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
+export VIRTUALENVWRAPPER_VIRTUALENV_ARGS=' -p /usr/bin/python3 '
+export PROJECT_HOME=$HOME/Devel
+source /usr/local/bin/virtualenvwrapper.sh
+ +
+

ノート: VIRTUALENVWRAPPER_PYTHONおよびVIRTUALENVWRAPPER_VIRTUALENV_ARGS変数は、Python3の通常のインストール場所を指し、source /usr/local/bin/virtualenvwrapper.shvirtualenvwrapper.sh スクリプトの通常の場所を指します。テスト時にvirtualenvが動作しない場合は、Pythonとスクリプトが予想される場所にあることを確認してから、起動ファイルを適切に変更してください。
+
+ あなたのシステムでの正しい場所は、which virtualenvwrapper.shwhich python3というコマンドを使って見つけることができます。

+
+ +

次に、ターミナルで次のコマンドを実行してスタートアップファイルをリロードします:

+ +
source ~/.bashrc
+ +

この時点で、以下に示すように一連のスクリプトが実行されているはずです:

+ +
virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/premkproject
+virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/postmkproject
+...
+virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/preactivate
+virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/postactivate
+virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/get_env_details
+
+ +

これで、mkvirtualenvコマンドを使用して新しい仮想環境を作成できます。

+ +

macOS X仮想環境のセットアップ

+ +

macOS Xでのvirtualenvwrapperのセットアップは、Ubuntuの場合とほぼ同じです(オフィシャルインストールガイドまたはそれ以下の指示に従います)。

+ +

次に示すようにpipを使用してvirtualenvwrapper(およびvirtualenvをバンドル)をインストールします。

+ +
sudo pip3 install virtualenvwrapper
+ +

次に、シェルスタートアップファイルの最後に次の行を追加します。

+ +
export WORKON_HOME=$HOME/.virtualenvs
+export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
+export PROJECT_HOME=$HOME/Devel
+source /usr/local/bin/virtualenvwrapper.sh
+
+ +
+

ノートVIRTUALENVWRAPPER_PYTHON変数はPython3の通常のインストール場所を指し、source /usr/local/bin/virtualenvwrapper.shvirtualenvwrapper.shスクリプトの通常の場所を指しています。テスト時にvirtualenvが動作しない場合は、Pythonとスクリプトが予想される場所にあることを確認してから、起動ファイルを適切に変更してください。

+ +

 

+ +

たとえば、macOSでの1つのインストールテストでは、スタートアップファイルに次の行が必要になりました:

+ +
export WORKON_HOME=$HOME/.virtualenvs
+export VIRTUALENVWRAPPER_PYTHON=/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
+export PROJECT_HOME=$HOME/Devel
+source /Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh
+ +

 

+ +

あなたのシステムでの正しい場所は、which virtualenvwrapper.shwhich python3というコマンドを使って見つけることができます。

+
+ +


+ これらはUbuntuの場合と同じ行ですが、スタートアップファイルはホームディレクトリ内で .bash_profile という別の名前の隠しファイルです。

+ +
+

ノート: 編集する.bash-profileがFinderで見つからない場合は、ターミナルでnanoを使用して開くこともできます。

+ +

コマンドは次のようになります:

+ +
cd ~  # Navigate to my home directory
+ls -la #List the content of the directory. YOu should see .bash_profile
+nano .bash_profile # Open the file in the nano text editor, within the terminal
+# Scroll to the end of the file, and copy in the lines above
+# Use Ctrl+X to exit nano, Choose Y to save the file.
+
+ +

 

+
+ +

ターミナルで次の呼び出しを行うことによって、スタートアップファイルをリロードします:

+ +
source ~/.bash_profile
+ +

この時点で、たくさんのスクリプトが実行されているのを見ることができます(Ubuntuのインストールと同じスクリプト)。mkvirtualenvコマンドを使用して新しい仮想環境を作成できるようになりました。

+ +

Windows 10仮想環境のセットアップ

+ +

virtualenvwrapper-winのインストールは、仮想環境情報を保存する場所(デフォルト値があります)を設定する必要がないため、virtualenvwrapperを設定するより簡単です。コマンドプロンプトで次のコマンドを実行するだけです:

+ +
pip3 install virtualenvwrapper-win
+ +

これで、mkvirtualenvコマンドで新しい仮想環境を作成できます。

+ +

仮想環境の作成

+ +

virtualenvwrapperまたはvirtualenvwrapper-winをインストールすると、仮想環境での作業はすべてのプラットフォームでほとんど同様になります。

+ +

mkvirtualenv コマンドを使用して新しい仮想環境を作成できます。このコマンドが実行されると、セットアップされる環境が表示されます(表示されるのはプラットフォーム固有のものです)。コマンドが完了すると、新しい仮想環境がアクティブになります。これは、プロンプトの開始が環境の名前(下に示すように)になるので、確認できます。

+ +
$ mkvirtualenv my_django_environment
+
+Running virtualenv with interpreter /usr/bin/python3
+...
+virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/t_env7/bin/get_env_details
+(my_django_environment) ubuntu@ubuntu:~$
+
+ +

これで、Djangoをインストールして開発を開始できる仮想環境の中に入りました。

+ +
+

ノート: これ以降、この記事(と実際にはモジュール)では、上でセットアップしたようなPython仮想環境内でコマンドが実行されると仮定してください。

+
+ +

仮想環境の使用

+ +

他にも知っておくべき便利なコマンドがいくつかあります(ツールのドキュメントには多くのものがありますが、これらはいつも使用するコマンドです):

+ + + +

Djangoのインストール

+ +

仮想環境を作成し、workonでその環境に入ってから、pip3を使用してDjangoをインストールできます。

+ +
pip3 install django
+
+ +

Djangoがインストールされていることをテストするには、次のコマンドを実行します(PythonがDjangoモジュールを見つけることができます):

+ +
# Linux/macOS X
+python3 -m django --version
+ 2.0
+
+# Windows
+py -3 -m django --version
+ 2.0
+
+ +
+

ノート: Windowsではpy -3コマンドをプレフィックスにしてPython 3スクリプトを起動し、Linux/macOS Xでは python3を実行します。

+
+ +
+

重要: このモジュールの残りの部分は、 Python 3 (python3) を呼び出すためにLinuxコマンドを使用します。Windowsで作業している場合は、単にこの接頭辞をpy -3に置き換えてください。

+
+ +

インストールのテスト

+ +

上記のテストはうまくいきますが、それほど楽しいことではありません。より面白いテストは、スケルトンプロジェクトを作成し、それが動作することを確認することです。これを行うには、コマンドプロンプト/ターミナルでDjangoアプリケーションを保存する場所に移動します。テストサイト用のフォルダを作成し、そのサイトに移動します。

+ +
mkdir django_test
+cd django_test
+
+ +

次に示すように、django-adminツールを使用して、 "mytestsite"という新しいスケルトンサイトを作成します。サイトを作成したら、manage.pyというプロジェクト管理用のメインスクリプトがあるフォルダに移動します。

+ +
django-admin startproject mytestsite
+cd mytestsite
+ +

次に示すようにmanage.pyrunserverコマンドを使用して、このフォルダ内から開発用Webサーバーを実行できます。

+ +
$ python3 manage.py runserver
+Performing system checks...
+
+System check identified no issues (0 silenced).
+
+You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
+Run 'python manage.py migrate' to apply them.
+
+December 29, 2017 - 03:03:47
+Django version 2.0, using settings 'mytestsite.settings'
+Starting development server at http://127.0.0.1:8000/
+Quit the server with CONTROL-C.
+
+ +
+

ノート: 上記のコマンドは、Linux/macOS Xコマンドを示しています。この時点では、 "14 unapplied migration(s)" という警告は無視できます!

+
+ +

サーバーが稼働したら、ローカルWebブラウザで http://127.0.0.1:8000/ というURLに移動して、サイトを表示できます。次のようなサイトが表示されます:

+ +

Django Skeleton App Homepage

+ + + +

要約

+ +

Django開発環境をあなたのコンピュータ上で稼働できるようになりました。

+ +

テストのセクションでは、django-admin startprojectを使用して新しいDjango Webサイトを作成する方法と、開発用Webサーバー(python3 manage.py runserver)を使用してブラウザで実行する方法についても簡単に説明しました。次の記事では、このプロセスを拡張して、シンプルで完全なWebアプリケーションを構築します。

+ +

参考文献

+ + + +

{{PreviousMenuNext("Learn/Server-side/Django/Introduction", "Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django")}}

+ +

このモジュール内

+ + + +

 

diff --git a/files/ja/learn/server-side/django/index.html b/files/ja/learn/server-side/django/index.html new file mode 100644 index 0000000000..cdb4304f5d --- /dev/null +++ b/files/ja/learn/server-side/django/index.html @@ -0,0 +1,69 @@ +--- +title: Djangoウェブフレームワーク (Python) +slug: Learn/Server-side/Django +tags: + - Python + - django + - ウェブアプリケーションフレームワーク + - サーバーサイドプログラミング + - プログラミング + - 初心者 + - 学習 + - 概要 +translation_of: Learn/Server-side/Django +--- +
{{LearnSidebar}}
+ +

Django は、Python で書かれた高機能なサーバーサイドウェブフレームワークで、とても普及しています。このモジュールは、Django が最も人気のあるウェブサーバーフレームワークの 1 つである理由、開発環境の設定方法、独自のウェブアプリケーションを作成する方法を説明します。

+ +

前提条件

+ +

このモジュールを進める前に、Django を知る必要はありません。理想は、サーバー・サイドのウェブサイトプログラミング第一歩 を読んで、サーバーサイドのウェブプログラミングとウェブフレームワークについて理解しておくことです。

+ +

プログラミングの概念と Python に関する一般的な知識はあるとよいですが、コアの概念を理解することは必須ではありません。

+ +
+

: Python は、初心者が読んで理解しやすい最も簡単なプログラミング言語の 1 つです。つまり、あなたがこのモジュールをより理解したいのであれば、インターネット上の多数の無料の書籍やチュートリアルがあなたを助けてくれます。(新しいプログラマーは python.org wiki の Python for Non Programmers ページをチェックすると良いでしょう。)

+
+ +

ガイド

+ +
+
Django の紹介
+
最初の Django の記事では、 "Django とは何ですか?" という疑問に答え、このウェブフレームワークの特徴と概要を説明します。主な機能の概要と、このモジュールで詳しく説明しない高度な機能などを紹介します。また、Django アプリケーションの主要な構成部品のいくつかを示して、使いはじめる前にどのように使うのか、何ができるのかを知っておきます。
+
Django 開発環境の設定
+
Django がどのようなものか知ったので、次は Windows、Linux (Ubuntu)、Mac OS X でDjango 開発環境をセットアップしてテストする方法を説明します。一般的なオペレーティングシステムを使っていれば、この記事で Django アプリケーションの開発を始められるでしょう。
+
Django チュートリアル: 地域図書館ウェブサイト
+
最初の記事は、実践的なチュートリアルで学習する内容を説明し、「地域図書館ウェブサイト」の概要を示します。このウェブサイトの例は、後の記事で作り進めていきます。
+
Django チュートリアル Part 2: ウェブサイトの骨組み作成
+
この記事は、基本的なウェブサイトプロジェクトの「骨組み」をどのように作っていくのかを示します。サイト固有の設定、URL、モデル、ビュー、テンプレートを作成する方法について説明します。
+
Django チュートリアル Part 3: モデルの使用
+
この記事は、地域図書館ウェブサイト用のモデルを定義する方法を示します ― モデルはアプリケーションのデータを格納するデータ構造を表し、Django はデータベースにデータを格納できます。モデルとは何か、どのように定義されるのか、および主要なフィールドタイプのいくつかを説明します。また、モデルデータにアクセスする主な方法のいくつかを簡単に示します。
+
Django チュートリアル Part 4: Django 管理サイト
+
地域図書館ウェブサイトのモデルを作成したので、Django 管理サイトを使用して実際の書籍データを追加します。最初に、管理サイトにモデルを登録する方法を示します。その後、ログインしてデータを作成する方法を示します。最後に、管理サイトの表示を改善する方法をいくつか示します。
+
Django チュートリアル Part 5: ホームページの作成
+
最初のページ全体を表示するコードを追加する準備が整いました。ここでは地域図書館ウェブサイトのホームページで各モデルタイプのレコード数を表示し、他のページへのサイドバーナビゲーションリンクを提供します。基本的な URL マップやビューを作成したり、データベースからレコードを取得したり、テンプレートを使用して実践的な経験を積むことができます。
+
Django チュートリアル Part 6: 汎用の一覧表示と詳細表示
+
このチュートリアルでは、地域図書館ウェブサイトを拡張し、書籍や著者の一覧と詳細ページを追加します。ここでは、汎用のクラスベースのビューについて学び、共通のユースケースのために書くコードの量をどのように減らせるかを示します。またURLのパターンマッチングがどのように行われるのか詳しく説明します。
+
Django チュートリアル Part 7: セッションフレームワーク
+
このチュートリアルでは、地域図書館ウェブサイトを拡張し、ホームページにセッションベースのアクセスカウンターを追加します。これは比較的簡単な例ですが、セッションフレームワークを使用して、自分のサイトの匿名ユーザーに永続的な動作を提供する方法を示しています。
+
Django チュートリアル Part 8: ユーザー認証と権限
+
このチュートリアルでは、ユーザーが自分のアカウントで自分のサイトにログインできるようにする方法と、ログインできるかどうかを制御する方法、ログインしているかどうか、アクセス許可によって表示する方法について説明します。このデモンストレーションの一環として、地域図書館ウェブサイトを拡張し、ログインページとログアウトページを追加し、貸し出された本を表示するためのユーザーとスタッフのページを追加します。
+
Django チュートリアル Part 9: フォームの操作
+
このチュートリアルでは、Django で HTML フォームを扱う方法、特にモデルインスタンスを作成、更新、削除するためのフォームを書く最も簡単な方法を紹介します。このデモンストレーションの一環として、図書館員が書籍を更新したり、管理アプリケーションを使用するのではなく独自のフォームを使用して著者の作成、更新、削除を行えるように、地域図書館ウェブサイトを拡張します。
+
Django チュートリアル Part 10: Django ウェブアプリケーションのテスト
+
ウェブサイトが成長するにつれて、手動でテストするのが困難になります。コンポーネント間のやりとりが複雑になるにつれて、ある領域の小さな変更が、他の領域へ影響がないか検証するためのテストの追加が多く必要になります。これらの問題を軽減する1つの方法は、変更を行うたびに簡単かつ確実に実行できる自動テストを作成することです。このチュートリアルでは、Django のテストフレームワークを使用して、あなたのウェブサイトの単体テストを自動化する方法を示します。
+
Django チュートリアル Part 11: Django を本番環境にデプロイする
+
これで、地域図書館の素晴らしいウェブサイトを作成 (およびテスト) できました。公開ウェブサーバーにインストールして、図書館のスタッフやメンバーがインターネット経由でアクセスできるようにしたいですね。この記事では、ウェブサイトを展開するホストを見つける方法と、サイトを実稼働のために必要な準備作業の概要について説明します。
+
Django ウェブアプリケーションセキュリティ
+
ユーザーデータの保護は、ウェブサイトの設計において不可欠な要素です。以前、ウェブセキュリティの記事でより一般的なセキュリティ上の脅威のいくつかについて説明しました。この記事では、Django の組み込み保護がそのような脅威をどのように処理するかを実践的に実演します。
+
+ +

課題

+ +

次の課題では、上記のガイドに記載されているように、Django を使用してウェブサイトを作成する方法を理解しているかテストします。

+ +
+
DIY Django ミニブログ
+
この課題では、このモジュールから学んだ知識の一部を使用して自分のブログを作成します。
+
diff --git a/files/ja/learn/server-side/django/introduction/index.html b/files/ja/learn/server-side/django/introduction/index.html new file mode 100644 index 0000000000..882c54bb56 --- /dev/null +++ b/files/ja/learn/server-side/django/introduction/index.html @@ -0,0 +1,281 @@ +--- +title: Djangoの紹介 +slug: Learn/Server-side/Django/Introduction +tags: + - Python + - Webフレームワーク + - django + - サーバーサイドプログラミング +translation_of: Learn/Server-side/Django/Introduction +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django")}}
+ +

最初のDjangoの記事では、 "Djangoとは何ですか?" という疑問に答え、このWebフレームワークの特徴と概要を説明します。主な機能の概要と、このモジュールで詳しく説明しない高度な機能などを紹介します。 また、Djangoアプリケーションの主要な構成部品のいくつかを示します。 (この時点ではまだテストできる開発環境を持っていません).

+ + + + + + + + + + + + +
前提条件:基本的なコンピューターリテラシーを持っていること。サーバーサイドウェブプログラミング の一般的な理解、特にウェブサイトにおけるクライントとサーバーのやりとりの仕組みを理解していること。
目的:Djangoが何であるか、Djangoの持つ機能、そしてDjangoアプリケーションの主要な構成部品に精通します。
+ +

Djangoとは何ですか?

+ +

Djangoは、安全でメンテナンス可能なWebサイトの迅速な開発を可能にする、高度なPython Webフレームワークです。経験豊富な開発者によって開発されたDjangoは、Web開発の多くの面倒事を引き受けてくれます。そのため車輪の再発明が不要で、アプリケーションを書くことに集中できます。無料でオープンソースであり、活発なコミュニティ、偉大なドキュメントがあります。また、無料と有料のサポートの多くのオプションもあります。 

+ +

Djangoの以下の特徴はソフトウェアを書くのに役立ちます:

+ +
+
完全
+
Djangoは "Batteries included" の哲学に従い、開発者が "すぐに" やりたいことのほとんどを提供します。必要なものはすべて1つの「製品」に含まれているため、すべてがシームレスに連携し、一貫した設計原則に従います。そして、豊富な最新のドキュメントが用意されています。
+
多彩
+
Djangoは、コンテンツ管理システムやWikiからソーシャルネットワーク、ニュースサイトなど、ほとんどのタイプのWebサイトを構築できます。任意のクライアントサイドのフレームワークで動作し、HTML、RSSフィード、JSON、XMLなどのほとんどの形式のコンテンツを配信できます。現在読んでいるサイトもDjangoベースですよ!
+
+ 内部的には、必要となるほとんどの機能(人気のあるデータベースやテンプレートエンジンなど)の選択肢を提供していますが、他のコンポーネントを使用するように拡張もできます。
+
安全
+
Djangoは、Webサイトを自動的に保護するために "正しいことをする" ように設計されたフレームワークです。多くの一般的なセキュリティミスを開発者が避けられるようにできています。例えば、セッション情報を脆弱な場所に置いたり、パスワードを直接保存するといった一般的なミスをDjangoでは避けるようになっています。セッション情報は、クッキーにセッションキーだけを格納し、実際のセッションデータはデータベースに保存されます。パスワードはパスワードハッシュをデータベースに格納します。このようにユーザーアカウントとパスワードを安全に管理する方法を提供しています。
+
+ パスワードハッシュは、送信されたパスワードから 暗号化ハッシュ関数を介して生成された固定長の値です。 Djangoは入力されたパスワードが正しいかどうかを、ハッシュ関数を介した値と保存されたハッシュ値を比較することでチェックできます。これは "一方向性" の機能であり、もし保存されているハッシュ値が侵害されても、攻撃者が元のパスワードを解読するのは困難です。
+
+ Djangoは、SQLインジェクション、クロスサイトスクリプティング(XSS)、クロスサイトリクエストフォージェリ(CSRF)、クリックジャッキングなどの多くの脆弱性に対する保護が有効です(これらの攻撃についての詳細は、 ウェブサイトのセキュリティ を参照してください)。
+
スケーラブル
+
Djangoはコンポーネントベースの “シェアードナッシング” アーキテクチャを採用しています(アーキテクチャの各部分は他と独立しており、必要に応じて置き換え、変更できます)。異なる部分を明確に分離しているため、キャッシュサーバー、データベースサーバー、アプリケーションサーバーの各ハードウェアをそれぞれ追加することによって、トラフィックの増加に合わせてスケールできるようになっています。いくつかの最も忙しいサイトは、ニーズを満たすためにDjangoを適切にスケールさせています(InstagramやDisqusなど)
+
メンテナンス可能
+
Djangoのコードは、保守可能で再利用可能になるような設計原則、デザインパターンを使って書かれています。特に、Do not Repeat Yourself(DRY)原則によって不要な複製がなく、コード量を削減します。Djangoは、関連する機能を再利用可能な "アプリケーション" にグループ化し、低いレベルでは関連するコードをモジュールにグループ化します(モデルビューコントローラ(MVC)パターンに沿っています)。
+
ポータブル
+
Djangoのコードは多くのプラットフォームで動作するPythonで書かれています。これはあなたがプラットフォームに縛られていないことを意味します。アプリケーションは多くの種類のLinux、Windows、Mac OS Xで実行できます。さらに、Djangoは多くのホスティングプロバイダによってよくサポートされています。Djangoサイトを特定のインフラストラクチャでホスティングするために、ドキュメントを提供していることが多いです。
+
+ +

どこから来たの?

+ +

Djangoは当初、2003年から2005年の間に、新聞のウェブサイトの作成とメンテナンスを担当するWebチームによって開発されました。いくつかのサイトを作成した後、チームは多くの共通コードとデザインパターンを除外、再利用するようになりました。この共通コードは、"Django" プロジェクトとして2005年7月にオープンソース化され、汎用のWeb開発フレームワークに発展しました。 

+ +

Djangoは、2008年9月の最初のマイルストーンリリース(1.0)から、最新のリリースバージョンである2.0(2017)まで、成長を続けています。 各リリースでは、新しいタイプのデータベース、テンプレートエンジン、キャッシュのサポートから、"汎用"ビュー機能とクラスの追加(プログラミングタスクで開発者が記述しなければならないコード量を削減します)などの新機能追加やバグフィックスがありました。 

+ +
+

ノート: DjangoのWebサイトの リリースノート をチェックして、最近のバージョンで何が変わったのか、どのような作業がDjangoを改善しているのか確認してください。

+
+ +

Djangoは現在、活発なオープンソースプロジェクトであり、何千人ものユーザーとコントリビュータがいます。元々の起源に関連するいくつかの機能はまだありますが、DjangoはあらゆるタイプのWebサイトを開発できる汎用フレームワークに進化しました。 

+ +

Djangoはどれくらい普及していますか?

+ +

サーバーサイドのフレームワークの普及率を決定的に測定する、すぐに利用できるものはありません (Hot Frameworks のようなサイトでは、GitHubプロジェクトの数や、各プラットフォームのStackOverflowの質問数をカウントするなどのメカニズムを使用して人気を評価しています) より良い質問は、「人気のないプラットフォームで問題を避けるために、Djangoは "人気がある" かどうか」、「それは進化し続けていますか?」「必要なときに助けを得ることができますか?」「Djangoを学べば、仕事を得る機会がありますか?」などです。

+ +

Djangoを使用している有名なサイトの数、コードベースにコントリビュートする人数、無料と有料の両方でサポートを提供する人数に基づいて、Djangoは普及しているフレームワークと言えるでしょう。

+ +

Djangoを使用している有名なサイト: Disqus、Instagram、Knight Foundation、MacArthur Foundation、Mozilla、National Geographic、Open Knowledge Foundation、Pinterest、Open Stack (ソース: Djangoホームページ)

+ +

Djangoはこだわりが強いですか?

+ +

Webフレームワークは、自身を "こだわりが強い" か "こだわりが強くない" と呼ぶことがあります。

+ +

こだわりが強いフレームワークは、特定のタスクを処理するための "正しい方法" についてこだわりを持っています。特定のドメイン(特定の種類の問題の解決)は、どのように扱うと正しいか、広く知られており、文書化もされているため、迅速な開発をサポートします。 しかし、主ドメイン以外の問題解決において柔軟性を欠き、使用できるコンポーネントのやアプローチの選択肢が少なくなる傾向があります。

+ +

対照的に、こだわりの強くないフレームワークは、目的を達成するための最善の結合されたコンポーネントの提供や、使用するコンポーネントを制限することが非常に少ないです。開発者は、特定のタスクを完了するために最も適したツールを簡単に使用できます。ただし、それらのコンポーネントを自分で見つける必要があります。
+
+ Djangoは "多少こだわりがある" ので、 "両方の世界のベスト" を提供します。 ほとんどのWeb開発タスクを処理するための一連のコンポーネントと、それを使う1つ(または2つ)の正しい方法を提供します。Djangoの分離アーキテクチャでは、通常、さまざまなオプションから選択しますが、必要に応じて新しいオプションを追加できます。

+ +

Djangoコードはどのように見えますか?

+ +

昔ながらのデータ駆動型Webサイトでは、WebアプリケーションはWebブラウザ(または他のクライアント)からのHTTPリクエストを待ちます。リクエストを受信すると、アプリケーションは、URLおよび、GET や POST データの情報に基づいて必要な処理を行います。 必要に応じてデータベースの情報を読み書きしたり、要求を満たすために必要なタスクを実行できます。 アプリケーションはWebブラウザに応答を返す際、検索したデータをHTMLテンプレートのプレースホルダに挿入し、動的にHTMLページを生成することがよくあります。

+ +

Django Webアプリケーションは、通常、これらの各ステップを処理するコードを別々のファイルにグループ化します:

+ +

+ + + +
+

ノート: Djangoはこの構成を "モデルビューテンプレート(Model View Template, MVT)" アーキテクチャと呼んでいます。これは Model View Controller アーキテクチャとよく似ています。 

+
+ + + +

以下のセクションでは、Djangoアプリケーションの主要部分の外観について説明します(開発環境を設定後、詳しく説明します)。

+ +

リクエストを正しいビューに送信する(urls.py)

+ +

URLマッパーは通常、urls.pyという名前のファイルに格納されます。以下の例では、マッパー(urlpatterns)はルート(特定のURLパターン) と対応するビュー関数のマッピングのリストを定義します。指定されたパターンと一致するURLを持つHTTPリクエストが受信されると、関連するビュー関数が呼び出され、リクエストを渡します。

+ +
urlpatterns = [
+    path('admin/', admin.site.urls),
+    path('book/<int:id>/', views.book-detail, name='book_detail'),
+    path('catalog/', include('catalog.urls')),
+    re_path(r'^([0-9]+)/$', views.best),
+]
+
+ +

 

+ +

urlpatternsオブジェクトはpath()re_path()関数のリストです(Pythonのリストは角括弧を使って定義され、アイテムはカンマ区切りです。末尾のカンマは任意です。例:  [item1, item2, item3,]

+ +

両方の関数の最初の引数は、一致させたいルート(パターン)です。path() 関数では、かぎ括弧を使って、ビュー関数に名前付き引数として渡されるURLの部分を定義します。 re_path() 関数では、柔軟なパターンマッチング方法として知られている正規表現を使います。 これらについては後の記事で説明します。

+ +

2つ目の引数は、パターンに一致したときに呼び出される別の関数です。views.book_detailという表記は、呼び出されたviewsモジュール内(views.pyという名前のファイル内部)で見つかるbook_detail()関数が呼び出されることを示します。

+ +

 

+ +

リクエストの処理(views.py)

+ +

ビューは、Webアプリケーションの中心であり、WebクライアントからHTTPリクエストを受け取り、HTTPレスポンスを返します。その中では、データベースにアクセスしたり、テンプレートをレンダリングしたりして、フレームワークの他のリソースを変換します。

+ +

以下の例は、前のセクションのURLマッパーによって呼び出される最小限の index() ビュー関数を示しています。すべてのビュー関数と同様に、HttpRequestオブジェクトをパラメータ(request)として受け取り、HttpResponseオブジェクトを返却します。この場合、リクエストには何もしません。レスポンスはハードコードされた文字列を返します。後のセクションで、もっと興味深いことをするリクエストを示します。

+ +
## filename: views.py (Django view functions)
+
+from django.http import HttpResponse
+
+def index(request):
+    # Get an HttpRequest - the request parameter
+    # perform operations using information from the request.
+    # Return HttpResponse
+    return HttpResponse('Hello from Django!')
+
+ +
+

ノート: Pythonについて少し:

+ + +
+ + + +

ビューは通常 views.py ファイルに格納します。

+ +

データモデルの定義(models.py)

+ +

Django Webアプリケーションは、モデルと呼ばれるPythonオブジェクトを通じてデータを管理し、クエリを実行します。モデルは、フィールドのタイプや、最大サイズ、デフォルト値、選択リストのオプション、ドキュメントのヘルプテキスト、フォームのラベルテキストなど、格納されるデータの構造を定義します。モデルの定義は、下層のデータベース(プロジェクト設定でいくつかから選択できます)からは独立しています。使用したいデータベースを選択したあとは、直接そのデータベースとやりとりする必要はありません。モデル構造と他のコードを書くだけで、Djangoはデータベースとのやりとりのすべての面倒な作業を処理します。

+ +

以下のコードスニペットは、Teamオブジェクトの非常に単純なDjangoモデルを示しています。Teamクラスは、Djangoのmodels.Modelクラスを継承しています。これは、チーム名とチームレベルを文字列フィールドとして定義し、各レコードに格納する最大文字数を指定します。team_levelはいくつかの値の一つになる可能性があります。したがって、この値を選択フィールドとして定義し、表示する選択項目と保存するデータの間のマッピングをデフォルト値とともに提供します。

+ +
# filename: models.py
+
+from django.db import models
+
+class Team(models.Model):
+    team_name = models.CharField(max_length=40)
+
+    TEAM_LEVELS = (
+        ('U09', 'Under 09s'),
+        ('U10', 'Under 10s'),
+        ('U11', 'Under 11s'),
+        ...  #list other team levels
+    )
+    team_level = models.CharField(max_length=3,choices=TEAM_LEVELS,default='U11')
+
+ +
+

ノート: Pythonについて少し:

+ + +
+ +

データの問い合わせ(views.py)

+ +

Djangoモデルは、データベースを検索するための簡単なクエリAPIを提供します。これは、さまざまな照合基準(例:完全一致、大文字小文字を区別しない、大なりなど)を使用して一度にいくつかのフィールドと照合でき、複雑なステートメントをサポートできます(たとえば、「U11チームのうち、"Fr"で始まるか"al"で終わる名前」)。

+ +

コードスニペットには、U09チームのすべてを表示するためのビュー機能(リソースハンドラ)が示されています。太字の線は、モデルクエリAPIを使用して、team_level フィールドに完全一致でテキスト 'U09' があるすべてのレコードをフィルタリングする方法を示しています。 (filter() 関数には、照合基準としてフィールド名とマッチタイプをダブルアンダースコアで区切った引数で渡していることに注意してください: team_level__exact)

+ +
## filename: views.py
+
+from django.shortcuts import render
+from .models import Team
+
+def index(request):
+    list_teams = Team.objects.filter(team_level__exact="U09")
+    context = {'youngest_teams': list_teams}
+    return render(request, '/best/index.html', context)
+
+ +
+
+ +

この関数は、ブラウザに返信されるHttpResponseを生成するために render() 関数を使います。この関数はショートカットです。指定されたHTMLテンプレートとテンプレートに挿入するいくつかのデータ("context"という名前の変数で提供される)を組み合わせてHTMLファイルを作成します。次のセクションでは、HTMLを作成するためにテンプレートにデータがどのように挿入されているかを示します。

+ +

データのレンダリング(HTMLテンプレート)

+ +

テンプレートシステムでは、出力ドキュメントの構造を指定できます。ページの生成時に埋められるデータはプレースホルダを使用します。テンプレートはHTMLを作成するためによく使われますが、他のタイプドキュメントも作成できます。Djangoはネイティブのテンプレートシステムと、Jinja2と呼ばれる一般的なPythonライブラリの両方をサポートしています。(必要に応じて他のシステムもサポートできます)

+ +

コードスニペットは、前のセクションの render()関数で呼び出されるHTMLテンプレートの外観を示しています。 このテンプレートは、レンダリング時にyoungest_teams というリスト変数(上記のrender()関数によってコンテキスト変数に含まれます)にアクセスできる前提で作成されています。HTMLスケルトンでは、youngest_teams変数が存在するかどうかを最初にチェックし、それを forループで繰り返す式があります。各繰り返しにおいて、テンプレートは各チームのteam_name値を{{htmlelement("li")}}要素に表示します。

+ +
## filename: best/templates/best/index.html
+
+<!DOCTYPE html>
+<html lang="en">
+<body>
+
+ {% if youngest_teams %}
+    <ul>
+    {% for team in youngest_teams %}
+        <li>\{\{ team.team_name \}\}</li>
+    {% endfor %}
+    </ul>
+{% else %}
+    <p>No teams are available.</p>
+{% endif %}
+
+</body>
+</html>
+ +

他に何ができますか?

+ +

前のセクションでは、ほとんどのWebアプリケーションで使用する主な機能(URLマッピング、ビュー、モデルおよびテンプレート)を示しました。Djangoが提供する他の機能のいくつかを紹介します:

+ + + +

要約

+ +

おめでとう、あなたはDjangoの旅の最初のステップを完了しました!Djangoの主なメリット、歴史について少し分かって、Djangoアプリケーションの主要部分のそれぞれがどのように見えるかを理解する必要があります。リスト、関数、クラスの構文も含めて、Pythonプログラミング言語についていくつか学んだことがあります。

+ +

上記では実際のDjangoコードをいくつか見ましたが、クライアントサイドのコードとは異なり、実行するための開発環境をセットアップする必要があります。それが次のステップです。

+ +
{{NextMenu("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django")}}
+ +

このモジュール内

+ + diff --git a/files/ja/learn/server-side/django/models/index.html b/files/ja/learn/server-side/django/models/index.html new file mode 100644 index 0000000000..fb3952f6b9 --- /dev/null +++ b/files/ja/learn/server-side/django/models/index.html @@ -0,0 +1,461 @@ +--- +title: 'Django チュートリアル Part 3: モデルの使用' +slug: Learn/Server-side/Django/Models +translation_of: Learn/Server-side/Django/Models +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django/Admin_site", "Learn/Server-side/Django")}}
+ +

この記事では、LocalLibrary Web サイトのモデルを定義する方法を説明します。モデルとは何か、その宣言方法、および主要なフィールドタイプについて説明します。また、モデルデータにアクセスするための主な方法のいくつかについても簡単に説明します。

+ + + + + + + + + + + + +
前提条件:Django チュートリアル Part 2: Web サイトの骨組み作成.
目標:適切なフィールドを選択しながら、独自のモデルを設計および作成できるようになる。
+ +

概要

+ +

Django web applications access and manage data through Python objects referred to as models. Models define the structure of stored data, including the field types and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc. The definition of the model is independent of the underlying database — you can choose one of several as part of your project settings. Once you've chosen what database you want to use, you don't need to talk to it directly at all — you just write your model structure and other code, and Django handles all the dirty work of communicating with the database for you.

+ +

This tutorial shows how to define and access the models for the LocalLibrary website example.

+ +

Designing the LocalLibrary models

+ +

Before you jump in and start coding the models, it's worth taking a few minutes to think about what data we need to store and the relationships between the different objects.

+ +

We know that we need to store information about books (title, summary, author, written language, category, ISBN) and that we might have multiple copies available (with globally unique id, availability status, etc.). We might need to store more information about the author than just their name, and there might be multiple authors with the same or similar names. We want to be able to sort information based on book title, author, written language, and category.

+ +

When designing your models it makes sense to have separate models for every "object" (a group of related information). In this case, the obvious objects are books, book instances, and authors.

+ +

You might also want to use models to represent selection-list options (e.g. like a drop down list of choices), rather than hard coding the choices into the website itself — this is recommended when all the options aren't known up front or may change. Obvious candidates for models, in this case, include the book genre (e.g. Science Fiction, French Poetry, etc.) and language (English, French, Japanese).

+ +

Once we've decided on our models and field, we need to think about the relationships. Django allows you to define relationships that are one to one (OneToOneField), one to many (ForeignKey) and many to many (ManyToManyField).

+ +

With that in mind, the UML association diagram below shows the models we'll define in this case (as boxes).

+ +

LocalLibrary Model UML

+ +

We've created models for the book (the generic details of the book), book instance (status of specific physical copies of the book available in the system), and author. We have also decided to have a model for the genre so that values can be created/selected through the admin interface. We've decided not to have a model for the BookInstance:status — we've hardcoded the values (LOAN_STATUS) because we don't expect these to change. Within each of the boxes, you can see the model name, the field names, and types, and also the methods and their return types.

+ +

The diagram also shows the relationships between the models, including their multiplicities. The multiplicities are the numbers on the diagram showing the numbers (maximum and minimum) of each model that may be present in the relationship. For example, the connecting line between the boxes shows that Book and a Genre are related. The numbers close to the Genre model show that a book must have one or more Genres (as many as you like), while the numbers on the other end of the line next to the Book model show that a Genre can have zero or many associated books.

+ +
+

Note: The next section provides a basic primer explaining how models are defined and used. As you read it, consider how we will construct each of the models in the diagram above.

+
+ +

Model primer

+ +

This section provides a brief overview of how a model is defined and some of the more important fields and field arguments.

+ +

Model definition

+ +

Models are usually defined in an application's models.py file. They are implemented as subclasses of django.db.models.Model, and can include fields, methods and metadata. The code fragment below shows a "typical" model, named MyModelName:

+ +
from django.db import models
+
+class MyModelName(models.Model):
+    """A typical class defining a model, derived from the Model class."""
+
+    # Fields
+    my_field_name = models.CharField(max_length=20, help_text='Enter field documentation')
+    ...
+
+    # Metadata
+    class Meta:
+        ordering = ['-my_field_name']
+
+    # Methods
+    def get_absolute_url(self):
+        """Returns the url to access a particular instance of MyModelName."""
+        return reverse('model-detail-view', args=[str(self.id)])
+
+    def __str__(self):
+        """String for representing the MyModelName object (in Admin site etc.)."""
+        return self.my_field_name
+ +

In the below sections we'll explore each of the features inside the model in detail:

+ +

Fields

+ +

A model can have an arbitrary number of fields, of any type — each one represents a column of data that we want to store in one of our database tables. Each database record (row) will consist of one of each field value. Let's look at the example seen below:

+ +
my_field_name = models.CharField(max_length=20, help_text='Enter field documentation')
+ +

Our above example has a single field called my_field_name, of type models.CharField — which means that this field will contain strings of alphanumeric characters. The field types are assigned using specific classes, which determine the type of record that is used to store the data in the database, along with validation criteria to be used when values are received from an HTML form (i.e. what constitutes a valid value). The field types can also take arguments that further specify how the field is stored or can be used. In this case we are giving our field two arguments:

+ + + +

The field name is used to refer to it in queries and templates. Fields also have a label, which is either specified as an argument (verbose_name) or inferred by capitalising the first letter of the field's variable name and replacing any underscores with a space (for example my_field_name would have a default label of My field name).

+ +

The order that fields are declared will affect their default order if a model is rendered in a form (e.g. in the Admin site), though this may be overridden.

+ +
Common field arguments
+ +

The following common arguments can be used when declaring many/most of the different field types:

+ + + +

There are many other options — you can view the full list of field options here.

+ +
Common field types
+ +

The following list describes some of the more commonly used types of fields. 

+ + + +

There are many other types of fields, including fields for different types of numbers (big integers, small integers, floats), booleans, URLs, slugs, unique ids, and other "time-related" information (duration, time, etc.). You can view the full list here.

+ +

Metadata

+ +

You can declare model-level metadata for your Model by declaring class Meta, as shown.

+ +
class Meta:
+    ordering = ['-my_field_name']
+
+ +

One of the most useful features of this metadata is to control the default ordering of records returned when you query the model type. You do this by specifying the match order in a list of field names to the ordering attribute, as shown above. The ordering will depend on the type of field (character fields are sorted alphabetically, while date fields are sorted in chronological order). As shown above, you can prefix the field name with a minus symbol (-) to reverse the sorting order.

+ +

So as an example, if we chose to sort books like this by default:

+ +
ordering = ['title', '-pubdate']
+ +

the books would be sorted alphabetically by title, from A-Z, and then by publication date inside each title, from newest to oldest.

+ +

Another common attribute is verbose_name, a verbose name for the class in singular and plural form:

+ +
verbose_name = 'BetterName'
+ +

Other useful attributes allow you to create and apply new "access permissions" for the model (default permissions are applied automatically), allow ordering based on another field, or to declare that the class is "abstract" (a base class that you cannot create records for, and will instead be derived from to create other models).

+ +

Many of the other metadata options control what database must be used for the model and how the data is stored (these are really only useful if you need to map a model to an existing database).

+ +

The full list of metadata options are available here: Model metadata options (Django docs).

+ +

Methods

+ +

A model can also have methods.

+ +

Minimally, in every model you should define the standard Python class method __str__() to return a human-readable string for each object. This string is used to represent individual records in the administration site (and anywhere else you need to refer to a model instance). Often this will return a title or name field from the model.

+ +
def __str__(self):
+    return self.field_name
+ +

Another common method to include in Django models is get_absolute_url(), which returns a URL for displaying individual model records on the website (if you define this method then Django will automatically add a "View on Site" button to the model's record editing screens in the Admin site). A typical pattern for get_absolute_url() is shown below.

+ +
def get_absolute_url(self):
+    """Returns the url to access a particular instance of the model."""
+    return reverse('model-detail-view', args=[str(self.id)])
+
+ +
+

Note: Assuming you will use URLs like /myapplication/mymodelname/2 to display individual records for your model (where "2" is the id for a particular record), you will need to create a URL mapper to pass the response and id to a "model detail view" (which will do the work required to display the record). The reverse() function above is able to "reverse" your url mapper (in the above case named 'model-detail-view') in order to create a URL of the right format.

+ +

Of course to make this work you still have to write the URL mapping, view, and template!

+
+ +

You can also define any other methods you like, and call them from your code or templates (provided that they don't take any parameters).

+ +

Model management

+ +

Once you've defined your model classes you can use them to create, update, or delete records, and to run queries to get all records or particular subsets of records. We'll show you how to do that in the tutorial when we define our views, but here is a brief summary.

+ +

Creating and modifying records

+ +

To create a record you can define an instance of the model and then call save().

+ +
# Create a new record using the model's constructor.
+record = MyModelName(my_field_name="Instance #1")
+
+# Save the object into the database.
+record.save()
+
+ +
+

Note: If you haven't declared any field as a primary_key, the new record will be given one automatically, with the field name id. You could query this field after saving the above record, and it would have a value of 1.

+
+ +

You can access the fields in this new record using the dot syntax, and change the values. You have to call save() to store modified values to the database.

+ +
# Access model field values using Python attributes.
+print(record.id) # should return 1 for the first record.
+print(record.my_field_name) # should print 'Instance #1'
+
+# Change record by modifying the fields, then calling save().
+record.my_field_name = "New Instance Name"
+record.save()
+ +

Searching for records

+ +

You can search for records that match certain criteria using the model's objects attribute (provided by the base class).

+ +
+

Note: Explaining how to search for records using "abstract" model and field names can be a little confusing. In the discussion below we'll refer to a Book model with title and genre fields, where genre is also a model with a single field name.

+
+ +

We can get all records for a model as a QuerySet, using objects.all(). The QuerySet is an iterable object, meaning that it contains a number of objects that we can iterate/loop through.

+ +
all_books = Book.objects.all()
+
+ +

Django's filter() method allows us to filter the returned QuerySet to match a specified text or numeric field against particular criteria. For example, to filter for books that contain "wild" in the title and then count them, we could do the following.

+ +
wild_books = Book.objects.filter(title__contains='wild')
+number_wild_books = wild_books.count()
+
+ +

The fields to match and the type of match are defined in the filter parameter name, using the format: field_name__match_type (note the double underscore between title and contains above). Above we're filtering title with a case-sensitive match. There are many other types of matches you can do: icontains (case insensitive), iexact (case-insensitive exact match), exact (case-sensitive exact match) and in, gt (greater than), startswith, etc. The full list is here.

+ +

In some cases you'll need to filter on a field that defines a one-to-many relationship to another model (e.g. a ForeignKey). In this case you can "index" to fields within the related model with additional double underscores. So for example to filter for books with a specific genre pattern, you will have to index to the name through the genre field, as shown below:

+ +
# Will match on: Fiction, Science fiction, non-fiction etc.
+books_containing_genre = Book.objects.filter(genre__name__icontains='fiction')
+
+ +
+

Note: You can use underscores (__) to navigate as many levels of relationships (ForeignKey/ManyToManyField) as you like. For example, a Book that had different types, defined using a further "cover" relationship might have a parameter name: type__cover__name__exact='hard'.

+
+ +

There is a lot more you can do with queries, including backwards searches from related models, chaining filters, returning a smaller set of values etc. For more information see Making queries (Django Docs).

+ +

Defining the LocalLibrary Models

+ +

In this section we will start defining the models for the library. Open models.py (in /locallibrary/catalog/). The boilerplate at the top of the page imports the models module, which contains the model base class models.Model that our models will inherit from.

+ +
from django.db import models
+
+# Create your models here.
+ +

Genre model

+ +

Copy the Genre model code shown below and paste it into the bottom of your models.py file. This model is used to store information about the book category — for example whether it is fiction or non-fiction, romance or military history, etc. As mentioned above, we've created the Genre as a model rather than as free text or a selection list so that the possible values can be managed through the database rather than being hard coded.

+ +
class Genre(models.Model):
+    """Model representing a book genre."""
+    name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)')
+
+    def __str__(self):
+        """String for representing the Model object."""
+        return self.name
+ +

The model has a single CharField field (name), which is used to describe the genre (this is limited to 200 characters and has some help_text. At the end of the model we declare a __str__() method, which simply returns the name of the genre defined by a particular record. No verbose name has been defined, so the field will be called Name in forms.

+ +

Book model

+ +

Copy the Book model below and again paste it into the bottom of your file. The book model represents all information about an available book in a general sense, but not a particular physical "instance" or "copy" available for loan. The model uses a CharField to represent the book's title and isbn (note how the isbn specifies its label as "ISBN" using the first unnamed parameter because the default label would otherwise be "Isbn"). The model uses TextField for the summary, because this text may need to be quite long.

+ +
from django.urls import reverse # Used to generate URLs by reversing the URL patterns
+
+class Book(models.Model):
+    """Model representing a book (but not a specific copy of a book)."""
+    title = models.CharField(max_length=200)
+
+    # Foreign Key used because book can only have one author, but authors can have multiple books
+    # Author as a string rather than object because it hasn't been declared yet in the file
+    author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
+
+    summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book')
+    isbn = models.CharField('ISBN', max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>')
+
+    # ManyToManyField used because genre can contain many books. Books can cover many genres.
+    # Genre class has already been defined so we can specify the object above.
+    genre = models.ManyToManyField(Genre, help_text='Select a genre for this book')
+
+    def __str__(self):
+        """String for representing the Model object."""
+        return self.title
+
+    def get_absolute_url(self):
+        """Returns the url to access a detail record for this book."""
+        return reverse('book-detail', args=[str(self.id)])
+
+ +

The genre is a ManyToManyField, so that a book can have multiple genres and a genre can have many books. The author is declared as ForeignKey, so each book will only have one author, but an author may have many books (in practice a book might have multiple authors, but not in this implementation!)

+ +

In both field types the related model class is declared as the first unnamed parameter using either the model class or a string containing the name of the related model. You must use the name of the model as a string if the associated class has not yet been defined in this file before it is referenced! The other parameters of interest in the author field are null=True, which allows the database to store a Null value if no author is selected, and on_delete=models.SET_NULL, which will set the value of the author to Null if the associated author record is deleted.

+ +

The model also defines __str__() , using the book's title field to represent a Book record. The final method, get_absolute_url() returns a URL that can be used to access a detail record for this model (for this to work we will have to define a URL mapping that has the name book-detail, and define an associated view and template).

+ +

BookInstance model

+ +

Next, copy the BookInstance model (shown below) under the other models. The BookInstance represents a specific copy of a book that someone might borrow, and includes information about whether the copy is available or on what date it is expected back, "imprint" or version details, and a unique id for the book in the library.

+ +

Some of the fields and methods will now be familiar. The model uses

+ + + +
import uuid # Required for unique book instances
+
+class BookInstance(models.Model):
+    """Model representing a specific copy of a book (i.e. that can be borrowed from the library)."""
+    id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular book across whole library')
+    book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True)
+    imprint = models.CharField(max_length=200)
+    due_back = models.DateField(null=True, blank=True)
+
+    LOAN_STATUS = (
+        ('m', 'Maintenance'),
+        ('o', 'On loan'),
+        ('a', 'Available'),
+        ('r', 'Reserved'),
+    )
+
+    status = models.CharField(
+        max_length=1,
+        choices=LOAN_STATUS,
+        blank=True,
+        default='m',
+        help_text='Book availability',
+    )
+
+    class Meta:
+        ordering = ['due_back']
+
+    def __str__(self):
+        """String for representing the Model object."""
+        return f'{self.id} ({self.book.title})'
+ +

We additionally declare a few new types of field:

+ + + +

The model __str__() represents the BookInstance object using a combination of its unique id and the associated Book's title.

+ +
+

Note: A little Python:

+ + +
+ +

Author model

+ +

Copy the Author model (shown below) underneath the existing code in models.py.

+ +
class Author(models.Model):
+    """Model representing an author."""
+    first_name = models.CharField(max_length=100)
+    last_name = models.CharField(max_length=100)
+    date_of_birth = models.DateField(null=True, blank=True)
+    date_of_death = models.DateField('Died', null=True, blank=True)
+
+    class Meta:
+        ordering = ['last_name', 'first_name']
+
+    def get_absolute_url(self):
+        """Returns the url to access a particular author instance."""
+        return reverse('author-detail', args=[str(self.id)])
+
+    def __str__(self):
+        """String for representing the Model object."""
+        return f'{self.last_name}, {self.first_name}'
+
+ +

All of the fields/methods should now be familiar. The model defines an author as having a first name, last name, and dates of birth and death (both optional). It specifies that by default the __str__() returns the name in last name, firstname order. The get_absolute_url() method reverses the author-detail URL mapping to get the URL for displaying an individual author.

+ +

Re-run the database migrations

+ +

All your models have now been created. Now re-run your database migrations to add them to your database.

+ +
python3 manage.py makemigrations
+python3 manage.py migrate
+ +

Language model — challenge

+ +

Imagine a local benefactor donates a number of new books written in another language (say, Farsi). The challenge is to work out how these would be best represented in our library website, and then to add them to the models.

+ +

Some things to consider:

+ + + +

After you've decided, add the field. You can see what we decided on Github here.

+ +

Don't forget that after a change to your model, you should again re-run your database migrations to add the changes.

+ +
python3 manage.py makemigrations
+python3 manage.py migrate
+ + + + + +

Summary

+ +

In this article we've learned how models are defined, and then used this information to design and implement appropriate models for the LocalLibrary website.

+ +

At this point we'll divert briefly from creating the site, and check out the Django Administration site. This site will allow us to add some data to the library, which we can then display using our (yet to be created) views and templates.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django/Admin_site", "Learn/Server-side/Django")}}

+ + + +

In this module

+ + diff --git a/files/ja/learn/server-side/django/skeleton_website/index.html b/files/ja/learn/server-side/django/skeleton_website/index.html new file mode 100644 index 0000000000..0d76ae46eb --- /dev/null +++ b/files/ja/learn/server-side/django/skeleton_website/index.html @@ -0,0 +1,398 @@ +--- +title: 'Django チュートリアル Part 2: スケルトンウェブサイトの作成' +slug: Learn/Server-side/Django/skeleton_website +tags: + - django + - イントロダクション + - ガイド + - チュートリアル + - 初心者 + - 学習 + - 記事 +translation_of: Learn/Server-side/Django/skeleton_website +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django/Models", "Learn/Server-side/Django")}}
+ +

Djangoチュートリアル の2つ目の記事では、基本的なウェブサイトプロジェクトの「スケルトン」をどのように作っていくのかを説明します。サイト固有の設定、URL、モデル、ビュー、テンプレートを作成する方法について説明します。

+ + + + + + + + + + + + +
前提条件:Django 開発環境の設定Djangoチュートリアルを確認してください。
目的:Djangoのツールを使って自分の新しいウェブサイトプロジェクトを開始できるようにする。
+ +

概要

+ +

この記事は、"スケルトン"ウェブサイトを作る方法を示します。そこにはサイト固有の設定、パス、モデル、ビューやテンプレートを組み込むことができるます。(これらについては後で述べます)

+ +

そのプロセスは単純です:

+ +
    +
  1. django-admin ツールを使ってプロジェクトフォルダ、基本的なテンプレートファイル、プロジェクト管理スクリプト(manage.py)を作ります .
  2. +
  3. manage.py は1つ以上のアプリケーションを作ります。 +
    +

    メモ: ウェブサイトは1つ以上のセクションから成ります。例えば、メインサイト、ブログ、ウィキ、ダウンロードエリアなど。Djangoは、これらのコンポーネントを別々のアプリケーションとして作成することを助けてくれます。それらは、必要なら異なるプロジェクトで再利用できます。

    +
    +
  4. +
  5. プロジェクトにアプリケーションを含めるために登録します。
  6. +
  7. url/path マッパーはそれらのアプリケーションを結びつけます。
  8. +
+ +

Local Library website のために、ウェブサイトフォルダとプロジェクトフォルダはlocallibrary という名前をつけます。また、1つのアプリケーションはcatalogという名前をつけます。 したがって、最上位のフォルダ構成は以下のようになります。:

+ +
locallibrary/         # Website foldermanage.py         # Script to run Django tools for this project (created using django-admin)
+    locallibrary/     # Website/project folder (created using django-admin)
+    catalog/          # Application folder (created using manage.py)
+
+ +

以下のセクションでは、その過程をもっと詳細に述べ、あなたが変更を試す方法を示しましょう。この記事の最後に、我々はいくつかの他のウェブサイトの設定について述べてみます。それはあなたがこのステージで行っていることかもしませんが。

+ +

プロジェクトの作成

+ +

始めにコマンドプロンプトまたはターミナルを開いて、(先に自分が仮想環境(virtual environment)にいることを確認して下さい)、Djangoアプリを格納したい場所へ移動します(ドキュメントフォルダの中など探しやすい場所にしましょう)。そして、新しいウェブサイトのフォルダ(この場合は locallibraryを作りましょう。そして、cdコマンドでそのフォルダへ移動しましょう。

+ +
mkdir locallibrary
+cd locallibrary
+ +

以下のように、django-admin startprojectコマンドで新しいプロジェクトを作り、そのフォルダの中に移動します。

+ +
django-admin startproject locallibrary
+cd locallibrary
+ +

django-adminツールは以下のようなフォルダ/ファイル構成を作ります。

+ +
locallibrary/manage.pylocallibrary/
+        settings.py
+        urls.py
+        wsgi.py
+ +

我々の現在の作業ディレクトリはこのようなものになっているでしょう。

+ +
../django_projects/locallibrary/
+ +

locallibraryプロジェクトのサブフォルダはこのウェブサイトに入口点となります: 

+ + + +

manage.py スクリプトはアプリケーションを作成したり、データベースを操作したり、webサーバを起動したりするのに使われます。

+ +

catalogアプリケーションの作成

+ +

次に、以下のコマンドを実行し、localibrary プロジェクトの中にアプリケーションを作りましょう。(このコマンドはプロジェクト内のmanage.pyと同じフォルダで実行する必要があります)

+ +
python3 manage.py startapp catalog
+ +
+

メモ: 上記コマンドは LinuxやmacOS X用です。Windows のコマンドは: py -3 manage.py startapp catalog

+ +

もしWindowsを使っているなら、このモジュール(manage.py)を使う際はpython3py -3 に変更して下さい。

+ +

もしPython 3.7.0以降を使用しているなら、py manage.py startapp catalogで使用できます。

+
+ +

このツールは新しいフォルダを作成し、アプリケーションの様々なパーツとなるファイルをそのフォルダに追加します(以下の太字で表示)。 ほとんどのファイルは目的に応じて便利な名前が付けられており(例えば ビューはviews.pyに、モジュールは models.pyに、テストはtests.pyに、管理サイトの設定は admin.pyに、アプリケーションの登録はapps.pyに保存する必要がある)、 さらに、関連するオブジェクトを操作するための最低限の定型的なコードを用意している。

+ +

アップデートされた後のプロジェクトディレクトリはこのようになる:

+ +
locallibrary/
+    manage.py
+    locallibrary/
+    catalog/
+        admin.py
+        apps.py
+        models.py
+        tests.py
+        views.py
+        __init__.py
+        migrations/
+
+ +

加えて今持っているものは:

+ + + +
+

メモ: 上記ファイルリストに何か欠けているものがあることに気づきましたか? ビューやモデルがある一方で、URLマッピング、テンプレート、静的ファイルの配置場所はありません。それらの作り方も以後説明します。(それらは全てのサイトで必須ではないですが、この例では必要になります。).

+
+ +

catalogアプリケーションの登録

+ +

アプリケーションが作成されたので、ツールを実行するために(例えばデータベースにモデルを追加する)プロジェクトに登録する必要がある。 アプリケーションの登録はプロジェクトの設定でINSTALLED_APPS リストに加えることで行えます。

+ +

プロジェクトの設定ファイル locallibrary/locallibrary/settings.py を開いて、INSTALLED_APPS リストの定義を見つけましょう。そして、以下のようにリストの最後に新しい行を追加しましょう。

+ +
INSTALLED_APPS = [
+    'django.contrib.admin',
+    'django.contrib.auth',
+    'django.contrib.contenttypes',
+    'django.contrib.sessions',
+    'django.contrib.messages',
+    'django.contrib.staticfiles',
+    'catalog.apps.CatalogConfig', 
+]
+ +

追加した新しい行はアプリケーションの構成オブジェクト(CatalogConfig) を指定しており、それはアプリケーション作成時に/locallibrary/catalog/apps.py によって生成されています。

+ +
+

メモ: すでにたくさんの他のINSTALLED_APPS (MIDDLEWAREも同様。設定ファイルのさらに下の方にあります)が存在していることに気づいたでしょう。これらは、Django administration site をサポートすること可能にし、その結果、Djangoが使用するたくさんの機能(セッション、認証など)をサポートします。

+
+ +

データベースの指定

+ +

これは、プロジェクトで使用するデータベースを特定する場所を指しています。— 開発と本番で動作のわずかな違いを避けるために、可能な限り同じデータベースを使用するのがよいでしょう。様々なDatabases オプションを確認することができます(Django docs)。

+ +

この例では、SQLite データベースを使いましょう。なぜなら、デモンストレーションデータベースでは多くの同時アクセスを必要とせず、セットアップ作業に追加の作業が不要だからです。このデータベースがどのように設定されているかは settings.py で確認できます。 (詳細は以下にも記載しています):

+ +
DATABASES = {
+    'default': {
+        'ENGINE': 'django.db.backends.sqlite3',
+        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
+    }
+}
+
+ +

SQLiteを使っているので、ここではこれ以上のセットアップは不要です。次へ移りましょう!

+ +

その他のプロジェクト設定

+ +

settings.py ファイルは、ほかのいくつかの設定の構成にも使用されますが、この時点では TIME_ZONE を変更するだけでよいでしょう。これは、tzデータベースタイムゾーンの標準リストの文字列を同じにする必要があります。(テーブルのTZ列に必要な値が含まれています) TIME_ZONE の値を、あなたのタイムゾーンに適した文字列に変更しましょう。
+ 例を示します:

+ +
TIME_ZONE = 'Europe/London'
+ +

今は変更しないが、次の2つの設定があることに注意してください。

+ + + +

URLマッパーの接続

+ +

Webサイトは、プロジェクトフォルダー内のURLマッパーファイル(urls.py)で作成されます。このファイルを使用してすべてのURLマッピングを管理できますが、関連付けられたアプリケーションへマッピングを延ばすのがより一般的です。

+ +

 locallibrary/locallibrary/urls.py を開いて、URLマッパーを使うためのいくつかの方法を記した説明文に注意してください。

+ +
"""locallibrary URL Configuration
+
+The `urlpatterns` list routes URLs to views. For more information please see:
+    https://docs.djangoproject.com/en/2.0/topics/http/urls/
+Examples:
+Function views
+    1. Add an import:  from my_app import views
+    2. Add a URL to urlpatterns:  path('', views.home, name='home')
+Class-based views
+    1. Add an import:  from other_app.views import Home
+    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
+Including another URLconf
+    1. Import the include() function: from django.urls import include, path
+    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
+"""
+from django.contrib import admin
+from django.urls import path
+
+urlpatterns = [
+    path('admin/', admin.site.urls),
+]
+
+ +

The URL mappings are managed through the urlpatterns variable, which is a Python list of path() functions. Each path() function either associates a URL pattern to a specific view, which will be displayed when the pattern is matched, or with another list of URL pattern testing code (in this second case, the pattern becomes the "base URL" for patterns defined in the target module). The urlpatterns list initially defines a single function that maps all URLs with the pattern admin/ to the module admin.site.urls , which contains the Administration application's own URL mapping definitions.

+ +
+

Note: The route in path() is a string defining a URL pattern to match. This string might include a named variable (in angle brackets), e.g. 'catalog/<id>/'. This pattern will match a URL like /catalog/any_chars/ and pass any_chars to the view as a string with parameter name id). We discuss path methods and route patterns further in later topics.

+
+ +

Add the lines below to the bottom of the file in order to add a new list item to the urlpatterns list. This new item includes a path() that forwards requests with the pattern catalog/ to the module catalog.urls (the file with the relative URL /catalog/urls.py).

+ +
# Use include() to add paths from the catalog application
+from django.conf.urls import include
+from django.urls import path
+
+urlpatterns += [
+    path('catalog/', include('catalog.urls')),
+]
+
+ +

Now let's redirect the root URL of our site (i.e. 127.0.0.1:8000) to the URL 127.0.0.1:8000/catalog/; this is the only app we'll be using in this project, so we might as well. To do this, we'll use a special view function (RedirectView), which takes as its first argument the new relative URL to redirect to (/catalog/) when the URL pattern specified in the path() function is matched (the root URL, in this case).

+ +

Add the following lines, again to the bottom of the file:

+ +
#Add URL maps to redirect the base URL to our application
+from django.views.generic import RedirectView
+urlpatterns += [
+    path('', RedirectView.as_view(url='/catalog/')),
+]
+ +

Leave the first parameter of the path function empty to imply '/'. If you write the first parameter as '/' Django will give you the following warning when you start the development server:

+ +
System check identified some issues:
+
+WARNINGS:
+?: (urls.W002) Your URL pattern '/' has a route beginning with a '/'.
+Remove this slash as it is unnecessary.
+If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'.
+
+ +

Django does not serve static files like CSS, JavaScript, and images by default, but it can be useful for the development web server to do so while you're creating your site. As a final addition to this URL mapper, you can enable the serving of static files during development by appending the following lines. 

+ +

Add the following final block to the bottom of the file now:

+ +
# Use static() to add url mapping to serve static files during development (only)
+from django.conf import settings
+from django.conf.urls.static import static
+
+urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
+
+ +
+

Note: There are a number of ways to extend the urlpatterns list (above we just appended a new list item using the += operator to clearly separate the old and new code). We could have instead just included this new pattern-map in the original list definition:

+ +
urlpatterns = [
+    path('admin/', admin.site.urls),
+    path('catalog/', include('catalog.urls')),
+    path('', RedirectView.as_view(url='/catalog/', permanent=True)),
+] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
+
+ +

In addition, we included the import line (from django.urls import include) with the code that uses it (so it is easy to see what we've added), but it is common to include all your import lines at the top of a Python file.

+
+ +

As a final step, create a file inside your catalog folder called urls.py, and add the following text to define the (empty) imported urlpatterns. This is where we'll add our patterns as we build the application. 

+ +
from django.urls import path
+from . import views
+
+
+urlpatterns = [
+
+]
+
+ +

ウェブサイトフレームワークのテスト

+ +

At this point we have a complete skeleton project. The website doesn't actually do anything yet, but its worth running it to make sure that none of our changes have broken anything. 

+ +

Before we do that, we should first run a database migration. This updates our database to include any models in our installed applications (and removes some build warnings).

+ +

Running database migrations

+ +

Django uses an Object-Relational-Mapper (ORM) to map Model definitions in the Django code to the data structure used by the underlying database. As we change our model definitions, Django tracks the changes and can create database migration scripts (in /locallibrary/catalog/migrations/) to automatically migrate the underlying data structure in the database to match the model.

+ +

When we created the website Django automatically added a number of models for use by the admin section of the site (which we'll look at later). Run the following commands to define tables for those models in the database (make sure you are in the directory that contains manage.py):

+ +
python3 manage.py makemigrations
+python3 manage.py migrate
+
+ +
+

Important: You'll need to run the above commands every time your models change in a way that will affect the structure of the data that needs to be stored (including both addition and removal of whole models and individual fields).

+
+ +

The makemigrations command creates (but does not apply) the migrations for all applications installed in your project (you can specify the application name as well to just run a migration for a single project). This gives you a chance to checkout the code for these migrations before they are applied — when you're a Django expert you may choose to tweak them slightly!

+ +

The migrate command actually applies the migrations to your database (Django tracks which ones have been added to the current database).

+ +
+

Note: See Migrations (Django docs) for additional information about the lesser-used migration commands.

+
+ +

Running the website

+ +

During development you can test the website by first serving it using the development web server, and then viewing it on your local web browser. 

+ +
+

Note: The development web server is not robust or performant enough for production use, but it is a very easy way to get your Django website up and running during development to give it a convenient quick test. By default it will serve the site to your local computer (http://127.0.0.1:8000/), but you can also specify other computers on your network to serve to. For more information see django-admin and manage.py: runserver (Django docs).

+
+ +

Run the development web server by calling the runserver command (in the same directory as manage.py):

+ +
python3 manage.py runserver
+
+ Performing system checks...
+
+ System check identified no issues (0 silenced).
+ September 22, 2016 - 16:11:26
+ Django version 1.10, using settings 'locallibrary.settings'
+ Starting development server at http://127.0.0.1:8000/
+ Quit the server with CTRL-BREAK.
+
+ +

Once the server is running you can view the site by navigating to http://127.0.0.1:8000/ in your local web browser. You should see a site error page that looks like this:

+ +

Django Debug page for Django 2.0

+ +

Don't worry! This error page is expected because we don't have any pages/urls defined in the catalogs.urls module (which we're redirected to when we get an URL to the root of the site). 

+ +
+

Note: The above page demonstrates a great Django feature — automated debug logging. An error screen will be displayed with useful information whenever a page cannot be found, or any error is raised by the code. In this case we can see that the URL we've supplied doesn't match any of our URL patterns (as listed). The logging will be turned off during production (when we put the site live on the Web), in which case a less informative but more user-friendly page will be served.

+
+ +

At this point we know that Django is working! 

+ +
+

Note: You should re-run migrations and re-test the site whenever you make significant changes. It doesn't take very long!

+
+ +

自分でやってみよう

+ +

The catalog/ directory contains files for the views, models, and other parts of the application. Open these files and inspect the boilerplate. 

+ +

As you saw above, a URL-mapping for the Admin site has already been added in the project's urls.py. Navigate to the admin area in your browser and see what happens (you can infer the correct URL from the mapping above).

+ + + +

要約

+ +

You have now created a complete skeleton website project, which you can go on to populate with urls, models, views, and templates.

+ +

Now the skeleton for the Local Library website is complete and running, it's time to start writing the code that makes this website do what it is supposed to do. 

+ +

参考文献

+ + + +

{{PreviousMenuNext("Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django/Models", "Learn/Server-side/Django")}}

+ +

このモジュール内

+ + diff --git a/files/ja/learn/server-side/django/tutorial_local_library_website/index.html b/files/ja/learn/server-side/django/tutorial_local_library_website/index.html new file mode 100644 index 0000000000..d0d0f670f2 --- /dev/null +++ b/files/ja/learn/server-side/django/tutorial_local_library_website/index.html @@ -0,0 +1,99 @@ +--- +title: 'Django チュートリアル: 地域図書館ウェブサイト' +slug: Learn/Server-side/Django/Tutorial_local_library_website +tags: + - Python + - django + - チュートリアル + - 初心者 +translation_of: Learn/Server-side/Django/Tutorial_local_library_website +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django")}}
+ +

実践的なチュートリアルシリーズの最初の記事は、学習する内容を説明し、後の記事で進めていく「地域図書館」のサンプルウェブサイトの概要を示しています。

+ + + + + + + + + + + + +
前提条件:Djangoの紹介を読んでください。以下の記事では、Django開発環境をセットアップする必要があります。
目的:このチュートリアルで使用されているサンプルアプリケーションを紹介し、読者が何をするかを理解できるようにします。
+ +

概要

+ +

MDN "地域図書館" Djangoチュートリアルへようこそ。ここでは、地域図書館のカタログを管理するためのWebサイトを開発します。

+ +

この一連のチュートリアルの記事でやることは次の通りです:

+ + + +

これらの話題のいくつかについて学び、他の話題にも簡単に触れました。チュートリアルシリーズの最後は、あなた自身で簡単なDjangoアプリケーションを開発するのに十分な知識が必要です。

+ +

地域図書館ウェブサイト

+ +

地域図書館(LocalLibrary)は、この一連のチュートリアルの過程で作成および展開するWebサイトの名前です。ご存じのように、ウェブサイトの目的は、利用可能な書籍を閲覧してアカウントを管理できる小さな地域図書館のオンラインカタログを提供することです。

+ +

この例は慎重に選択されています。なぜなら、必要に応じて細かく表示することができ、ほぼすべてのDjango機能を表示するために使用できます。 さらに重要なことは、Django Webフレームワークの最も重要な機能をガイドする方法を提供できることです:

+ + + +

これは非常に拡張可能な例ですが、地域図書館と呼んでいます。理由は、Djangoをすぐに起動して実行するのに役立つ最小限の情報を表示したいと考えているからです。つまり、書籍、本のコピー、作者関する情報、およびその他の重要な情報は保存します。しかし、図書館が保管する可能性のある他のアイテムに関する情報を保管したり、複数の図書館サイトやその他の「大きな図書館」機能をサポートするために必要なインフラストラクチャーを提供することはありません。

+ +

詰まってます、どこでソースを入手できますか?

+ +

チュートリアルを進めるうちに、各ポイントでコピー&ペーストするための適切なコードスニペットが提供されます。また、この他に自分で拡張してほしいコードもあります(いくつかのガイダンスがあります)。

+ +

詰まった場合は、ウェブサイトの完全に開発されたバージョンをGithub上で見ることができます。

+ +

要約

+ +

地域図書館ウェブサイトについてと、何を学ぶのかをもう少し知りました。今度は例を含むスケルトンプロジェクトを作成しましょう。

+ +

{{PreviousMenuNext("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django")}}

+ +

 

+ +

このモジュール内

+ + + +

 

diff --git a/files/ja/learn/server-side/django/web_application_security/index.html b/files/ja/learn/server-side/django/web_application_security/index.html new file mode 100644 index 0000000000..496fac0fbd --- /dev/null +++ b/files/ja/learn/server-side/django/web_application_security/index.html @@ -0,0 +1,180 @@ +--- +title: Django Web アプリケーションのセキュリティ +slug: Learn/Server-side/Django/web_application_security +translation_of: Learn/Server-side/Django/web_application_security +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/Deployment", "Learn/Server-side/Django/django_assessment_blog", "Learn/Server-side/Django")}}
+ +
ユーザーのデータを守ることはWebデザインにおいて重要です。 以前、より一般的なセキュリティの脅威の一部を Webセキュリティ の記事で説明しました— 本記事ではDjangoにビルトインされている保護機能がそのような脅威にどう対応しているか、より実践的な動きを見ながら説明していきます。
+ + + + + + + + + + + + +
前提条件:Read the サーバーサイドプログラミングの "Webサイトセキュリティ" の記事を読んでいること。Djangoチュートリアルを少なくとも Django Tutorial Part 9: Working with forms まで完了していること。
目標:Django Webアプリケーションをセキュアにするためにやるべきこと、やってはいけないことを理解する。
+ +

概要

+ +

The Website security topic provides an overview of what website security means for server-side design, and some of the more common threats that you may need to protect against. One of the key messages in that article is that almost all attacks are successful when the web application trusts data from the browser.

+ +
+

Important: The single most important lesson you can learn about website security is to never trust data from the browser. This includes GET request data in URL parameters, POST data, HTTP headers and cookies, user-uploaded files, etc. Always check and sanitize all incoming data. Always assume the worst.

+
+ +

The good news for Django users is that many of the more common threats are handled by the framework! The Security in Django (Django docs) article explains Django's security features and how to secure a Django-powered website.

+ +

Common threats/protections

+ +

Rather than duplicate the Django documentation here, in this article we'll demonstrate just a few of the security features in the context of our Django LocalLibrary tutorial.

+ +

Cross site scripting (XSS)

+ +

XSS is a term used to describe a class of attacks that allow an attacker to inject client-side scripts through the website into the browsers of other users. This is usually achieved by storing malicious scripts in the database where they can be retrieved and displayed to other users, or by getting users to click a link that will cause the attacker’s JavaScript to be executed by the user’s browser.

+ +

Django's template system protects you against the majority of XSS attacks by escaping specific characters that are "dangerous" in HTML. We can demonstrate this by attempting to inject some JavaScript into our LocalLibrary website using the Create-author form we set up in Django Tutorial Part 9: Working with forms.

+ +
    +
  1. Start the website using the development server (python3 manage.py runserver).
  2. +
  3. Open the site in your local browser and login to your superuser account.
  4. +
  5. Navigate to the author-creation page (which should be at URL: http://127.0.0.1:8000/catalog/author/create/).
  6. +
  7. Enter names and date details for a new user, and then append the following text to the Last Name field:
    + <script>alert('Test alert');</script>.
    + Author Form XSS test +
    +

    Note: This is a harmless script that, if executed, will display an alert box in your browser. If the alert is displayed when you submit the record then the site is vulnerable to XSS threats.

    +
    +
  8. +
  9. Press Submit to save the record.
  10. +
  11. When you save the author it will be displayed as shown below. Because of the XSS protections the alert() should not be run. Instead the script is displayed as plain text.Author detail view XSS test
  12. +
+ +

If you view the page HTML source code, you can see that the dangerous characters for the script tags have been turned into their harmless escape code equivalents (e.g. > is now &gt;)

+ +
<h1>Author: Boon&lt;script&gt;alert(&#39;Test alert&#39;);&lt;/script&gt;, David (Boonie) </h1>
+
+ +

Using Django templates protects you against the majority of XSS attacks. However it is possible to turn off this protection, and the protection isn't automatically applied to all tags that wouldn't normally be populated by user input (for example, the help_text in a form field is usually not user-supplied, so Django doesn't escape those values).

+ +

It is also possible for XSS attacks to originate from other untrusted source of data, such as cookies, Web services or uploaded files (whenever the data is not sufficiently sanitized before including in a page). If you're displaying data from these sources, then you may need to add your own sanitisation code.

+ +

Cross site request forgery (CSRF) protection

+ +

CSRF attacks allow a malicious user to execute actions using the credentials of another user without that user’s knowledge or consent. For example consider the case where we have a hacker who wants to create additional authors for our LocalLibrary.

+ +
+

Note: Obviously our hacker isn't in this for the money! A more ambitious hacker could use the same approach on other sites to perform much more harmful tasks (e.g. transfer money to their own accounts, etc.)

+
+ +

In order to do this, they might create an HTML file like the one below, which contains an author-creation form (like the one we used in the previous section) that is submitted as soon as the file is loaded. They would then send the file to all the Librarians and suggest that they open the file (it contains some harmless information, honest!). If the file is opened by any logged in librarian, then the form would be submitted with their credentials and a new author would be created.

+ +
<html>
+<body onload='document.EvilForm.submit()'>
+
+<form action="http://127.0.0.1:8000/catalog/author/create/" method="post" name='EvilForm'>
+  <table>
+    <tr><th><label for="id_first_name">First name:</label></th><td><input id="id_first_name" maxlength="100" name="first_name" type="text" value="Mad" required /></td></tr>
+    <tr><th><label for="id_last_name">Last name:</label></th><td><input id="id_last_name" maxlength="100" name="last_name" type="text" value="Man" required /></td></tr>
+    <tr><th><label for="id_date_of_birth">Date of birth:</label></th><td><input id="id_date_of_birth" name="date_of_birth" type="text" /></td></tr>
+    <tr><th><label for="id_date_of_death">Died:</label></th><td><input id="id_date_of_death" name="date_of_death" type="text" value="12/10/2016" /></td></tr>
+  </table>
+  <input type="submit" value="Submit" />
+</form>
+
+</body>
+</html>
+
+ +

Run the development web server, and log in with your superuser account. Copy the text above into a file and then open it in the browser. You should get a CSRF error, because Django has protection against this kind of thing!

+ +

The way the protection is enabled is that you include the {% csrf_token %} template tag in your form definition. This token is then rendered in your HTML as shown below, with a value that is specific to the user on the current browser.

+ +
<input type='hidden' name='csrfmiddlewaretoken' value='0QRWHnYVg776y2l66mcvZqp8alrv4lb8S8lZ4ZJUWGZFA5VHrVfL2mpH29YZ39PW' />
+
+ +

Django generates a user/browser specific key and will reject forms that do not contain the field, or that contain an incorrect field value for the user/browser.

+ +

To use this type of attack the hacker now has to discover and include the CSRF key for the specific target user. They also can't use the "scattergun" approach of sending a malicious file to all librarians and hoping that one of them will open it, since the CSRF key is browser specific.

+ +

Django's CSRF protection is turned on by default. You should always use the {% csrf_token %} template tag in your forms and use POST for requests that might change or add data to the database.

+ +

Other protections

+ +

Django also provides other forms of protection (most of which would be hard or not particularly useful to demonstrate):

+ +
+
SQL injection protection
+
SQL injection vulnerabilities enable malicious users to execute arbitrary SQL code on a database, allowing data to be accessed, modified, or deleted irrespective of the user's permissions. In almost every case you'll be accessing the database using Django’s querysets/models, so the resulting SQL will be properly escaped by the underlying database driver. If you do need to write raw queries or custom SQL then you'll need to explicitly think about preventing SQL injection.
+
Clickjacking protection
+
In this attack a malicious user hijacks clicks meant for a visible top level site and routes them to a hidden page beneath. This technique might be used, for example, to display a legitimate bank site but capture the login credentials in an invisible <iframe> controlled by the attacker. Django contains clickjacking protection in the form of the X-Frame-Options middleware which, in a supporting browser, can prevent a site from being rendered inside a frame.
+
Enforcing SSL/HTTPS
+
SSL/HTTPS can be enabled on the web server in order to encrypt all traffic between the site and browser, including authentication credentials that would otherwise be sent in plain text (enabling HTTPS is highly recommended). If HTTPS is enabled then Django provides a number of other protections you can use:
+
+ + + +
+
Host header validation
+
Use ALLOWED_HOSTS to only accept requests from trusted hosts.
+
+ +

There are many other protections, and caveats to the usage of the above mechanisms. While we hope that this has given you an overview of what Django offers, you should still read the Django security documentation.

+ + + +

Summary

+ +

Django has effective protections against a number of common threats, including XSS and CSRF attacks. In this article we've demonstrated how those particular threats are handled by Django in our LocalLibrary website. We've also provided a brief overview of some of the other protections.

+ +

This has been a very brief foray into web security. We strongly recommend that you read Security in Django to gain a deeper understanding.

+ +

The next and final step in this module about Django is to complete the assessment task.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/Server-side/Django/Deployment", "Learn/Server-side/Django/django_assessment_blog", "Learn/Server-side/Django")}}

+ +

 

+ +

In this module

+ + + +

 

-- cgit v1.2.3-54-g00ecf