Djangoチュートリアルの開始では、Djangoサイトを起動して実行する方法を説明しました。 ただし、レンダリングしたテンプレートは非常に基本的なものでした。

これは間違いなくあなたがあなたのサイトをどのように見せたいかではありません。

どのようにしてサイトの見栄えを良くしますか? 単純! いくつかのスタイリングを追加します。 このチュートリアルでは、CSSとJavaScriptをDjangoテンプレートに追加して、見栄えを良くする方法を紹介します。 そのためには、まずDjangoの静的ファイルの概念を理解する必要があります。

Djangoプロジェクトのセットアップ

テスト用のDjangoプロジェクトを設定しましょう。 まず、アプリが存在するprojectsというフォルダーを作成します。

mkdir projects && cd projects

projects内で、virtualenvを使用して、アプリの依存関係のための環境を作成しましょう。

virtualenv env --python python3

注:virtualenvがインストールされていない場合は、コマンドpip install virtualenvを使用してインストールしてください。

それが完了したら、アクティベートシェルスクリプトを実行して環境をアクティベートします。

source env/bin/activate

そのコマンドが機能する場合は、端末に(env)プロンプトが表示されます。

#(env)~/projects
$

すべてがうまく見えますか? 素晴らしい! 次に、pipを使用して、Djangoを環境にインストールします。

#(env)~/projects
$ pip install django

このコマンドは、Djangoを環境にインストールする必要があります。 執筆時点では、Djangoのバージョンは1.10.4です。

次に、django-adminスクリプトを呼び出して、Djangoアプリを作成します。 このようにしましょう:

#(env)~/projects
$ django-admin startproject djangotemplates

projectsフォルダー構造を確認すると、以前に作成したenvフォルダーに加えて、Djangoによって作成されたdjangotemplatesという新しいフォルダーが作成されます。

cddjangotemplatesに。

これで、フォルダ構造は次のようになります。

djangotemplates
--djangotemplates
----**init**.py
----settings.py
----urls.py
----wsgi.py
--manage.py

全部終わった? これで、開始する準備が整いました。

静的ファイルを管理するための設定

静的ファイルには、CSS、JavaScript、画像など、サイトと一緒に提供したいものが含まれます。 Djangoは、静的ファイルをどのように含めるべきかについて非常に意見が分かれています。 この記事では、静的ファイルをDjangoアプリケーションに追加する方法を紹介します。

内側のdjangotemplatesフォルダー内のsettings.pyファイルを開きます。 ファイルの一番下に、次の行が表示されます。

# djangotemplates/djangotemplates/settings.py

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'

この行は、静的ファイルを検索するときにベースURL(この場合はlocalhost:8000)に静的を追加するようにDjangoに指示します。 Djangoでは、staticフォルダーをほぼどこにでも配置できます。 複数のstaticフォルダを作成することもできます。 各アプリに1つ。 ただし、簡単にするために、プロジェクトフォルダーのルートにあるstaticフォルダーを1つだけ使用します。 後で作成します。 とりあえず、settings.pyファイルに次のように行を追加してみましょう。

# djangotemplates/djangotemplates/settings.py

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'

# Add these new lines
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

STATICFILES_DIRSタプルは、特定のアプリに関連付けられていない静的ファイルを探す場所をDjangoに指示します。 この場合、アプリだけでなく、ルートフォルダー内のstaticというフォルダー内の静的ファイルも検索するようにDjangoに指示しました。

Djangoは、静的ファイルを1つの場所に収集して、簡単に提供できるようにするメカニズムも提供します。 collectstaticコマンドを使用して、Djangoはアプリ内のすべての静的ファイルを検索し、指示された場所でそれらを収集します。 STATIC_ROOT。 この例では、python manage.py collectstaticを実行するときに、すべての静的ファイルをプロジェクトルートディレクトリのstaticfilesというフォルダーに収集するようにDjangoに指示しています。 この機能は、特に本番環境で静的ファイルを提供する場合に非常に便利です。

アプリのセットアップ

内側のdjangotemplatesフォルダーおよびmanage.pyファイルと同じレベルにstaticというフォルダーを作成します。 これで、次の構造になります。

djangotemplates
--djangotemplates
----**init**.py
----settings.py
----urls.py
----wsgi.py
--static
--manage.py

このフォルダー内には、作成するカスタムCSSとJSがあります。 その点で、静的フォルダー内にファイルを保持する2つのフォルダーを追加しましょう。1つはcssと呼ばれ、もう1つはjsと呼ばれます。 css内に、main.cssというファイルを作成します。 jsフォルダにもmain.jsを追加します。 静的フォルダは次のようになります。

--static
----css
------main.cs
----js
------main.js

それが終わったら、作業するexampleという新しいDjangoアプリを作成しましょう。 その方法を覚えていますか? 心配しないでください、それは非常に簡単です。

#(env)~/projects/djangotemplates
$ python manage.py startapp example

これが完了すると、djangotemplatesおよびstaticの横にexampleというフォルダーが作成されます。 そしてもちろん、あなたはまだmanage.pyファイルを見ることができるはずです。

djangotemplates
--djangotemplates
----**init**.py
----settings.py
----urls.py
----wsgi.py
--example
--static
--manage.py

新しいアプリについてDjangoに伝える必要があります。 内側のdjangotemplatesフォルダーに移動し、settings.pyを開いて、INSTALLED_APPSを探します。 含まれている他のアプリの下にexampleを追加します。

# djangotemplates/djangotemplates/settings.py

DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'example', # Add this line
]

要約すると、次のフォルダ構造になりました。

djangotemplates
--djangotemplates
----**init**.py
----settings.py
----urls.py
----wsgi.py
--example
----migrations
------**init**.py
----admin.py
----apps.py
----models.py
----tests.py
----views.py
--static
----css
------main.cs
----js
------main.js
--manage.py

URL定義

新しいアプリに移動するためのURLを定義しましょう。 djangotemplates/djangotemplates/urls.pyを編集してそれを実現しましょう。

# djangotemplates/djangotemplates/urls.py

from django.conf.urls import url, include # Add include to the imports here
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('example.urls')) # tell django to read urls.py in example app
]

その後、exampleアプリフォルダーに、urls.pyという名前の新しいファイルを作成し、次のコードを追加します。

# djangotemplates/example/urls.py

from django.conf.urls import url
from example import views

urlpatterns = [
    url(r'^$', views.HomePageView.as_view(), name='home'), # Notice the URL has been named
    url(r'^about/$', views.AboutPageView.as_view(), name='about'),
]

今書いたコードは、空のルート(つまり、localhost:8000)をHomePageViewというビューに一致させ、ルート/about/AboutPageViewというビューに一致させるようにDjangoに指示します。 DjangoビューはHTTPリクエストを受け取り、HTTPレスポンスを返すことを忘れないでください。 この例では、ホームページテンプレートを返すTemplateViewと、Aboutページ用の別のテンプレートを使用します。 これを行うには、exampleアプリフォルダー内に、templatesという別のフォルダーを作成します。 新しいtemplatesフォルダー内に、index.htmlおよびabout.htmlという2つの新しいファイルを作成します。 これで、exampleアプリフォルダーは次の構造になります。

--example
----migrations
------**init**.py
----templates
------index.html
------about.html
----admin.py
----apps.py
----models.py
----tests.py
----urls.py
----views.py

index.html内に、次のコードを貼り付けます。

<!-- djangotemplates/example/templates/index.html-->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Welcome Home</title>
</head>
<body>
  <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
    Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
    Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
  </p>
  <a href="{% url 'home' %}">Go Home</a>
  <a href="{% url 'about' %}">About This Site</a>
</body>
</html>

このコードをabout.htmlに追加します。

<!-- djangotemplates/example/templates/about.html-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>About Us</title>
</head>
<body>
  <p>
  We are a group of Django enthusiasts with the following idiosyncrasies:

  <ol>
    <li>We only eat bananas on Saturdays.</li>
    <li>We love making playing football on rainy days.</li>
  </ol>
  </p>
  <a href="{% url 'home' %}">Go Home</a>
  <a href="{% url 'about' %}">About This Site</a>
</body>
</html>

テンプレートでGo HomeおよびAbout This Siteのリンクを参照していることに注目してください。 urls.pyでURLに名前を付けたため、Djangoの自動URL逆引き参照を使用できます。 きちんと、ハァッ!

このコードの効果は次のセクションで確認します。

ビューの配線

テンプレートを提供するための最終的なコードを追加しましょう。 このためにdjangotemplates/example/views.pyを編集する必要があります。

# djangotemplates/example/views.py
from django.shortcuts import render
from django.views.generic import TemplateView # Import TemplateView

# Add the two views we have been talking about  all this time :)
class HomePageView(TemplateView):
    template_name = "index.html"


class AboutPageView(TemplateView):
    template_name = "about.html"

これで、アプリを実行できます。 アプリを実行するのはこれが初めてなので、最初にDjangoのデフォルトの移行を行う必要があります。

#(env)~/projects/djangotemplates
$ python manage.py migrate

それが完了したら、サーバーを起動します。

#(env)~/projects/djangotemplates
$ python manage.py runserver

ブラウザを開き、http://localhost:8000に移動します。 あなたは私たちのホームページを見ることができるはずです。

下部にあるリンクをクリックすると、ページ間を移動できるはずです。 これがAboutページです:

テンプレートの継承

exampleアプリフォルダー内のテンプレートフォルダーに焦点を移してみましょう。 現在、index.htmlabout.htmlの2つのテンプレートが含まれています。

これらのテンプレートの両方にCSSを含める必要があります。 両方で同じコードを書き直す代わりに、Djangoでは両方が継承するベーステンプレートを作成できます。 これにより、共有されているものを変更する必要があるときに、テンプレートに多くの繰り返しコードを記述する必要がなくなります。

それでは、ベーステンプレートを作成しましょう。 djangotemplates/example/templatesbase.htmlというファイルを作成します。 その中にこのコードを書いてください:

<!-- djangotemplates/example/templates/base.html -->

{% load static %}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>
      Django Sample Site - {% block title %}{% endblock %}
    </title>

    <script src="{% static 'js/main.js' %}"></script> <!-- This is how to include a static file -->
    <link rel="stylesheet" href="{% static 'css/main.css' %}" type="text/css" />
  </head>
  <body>
    <div class="container">
      {% block pagecontent %}
      {% endblock %}
    </div>
  </body>
</html>

ファイルの最初の行である{% load static %}は、Djangoの特別なテンプレートタグ構文を使用して、このテンプレートのstaticフォルダー内のファイルを使用するようにテンプレートエンジンに指示します。

タイトルタグでは、Djangoブロックを使用しています。 これが意味するのは、このベーステンプレートから継承するDjangoテンプレートでは、titleという名前のブロック内にあるHTMLがタイトルブロックにプラグインされるということです。 bodyタグのpagecontentブロックについても同じことが言えます。 これが紛らわしいように聞こえても、心配しないでください。 すぐに動作するのがわかります。

Djangoサーバーを実行していない場合は、ターミナルでpython manage.py runserverを実行して実行します。 http:// localhost:8000に移動します。 前のテンプレートが表示されます。

次に、index.htmlテンプレートを編集して、ベーステンプレートから継承します。

<!-- djangotemplates/example/templates/index.html -->

{% extends 'base.html' %} <!-- Add this for inheritance -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Welcome Home</title>
</head>
<body>
    <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
      Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
      Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
      Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    </p>
    <a href="{% url 'home' %}">Go Home</a>
    <a href="{% url 'about' %}">About This Site</a>
</body>
</html>

ブラウザにページをリロードします。 何も表示されません! これは、Djangoは、コンテンツがレンダリングできるように、ベーステンプレートで定義したブロック内に書き込まれることを想定しているためです。 index.htmlを編集して、ブロックを追加します。

<!-- djangotemplates/example/templates/index.html -->

{% extends 'base.html' %}

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>{% block title %}Welcome Home {% endblock %}</title>
</head>
<body>
  {% block pagecontent %}
    <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
      Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
      Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
      Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    </p>
    <a href="{% url 'home' %}">Go Home</a>
    <a href="{% url 'about' %}">About This Site</a>
  {% endblock %}
</body>
</html>

ブラウザでページをリロードして出来上がり! コンテンツが再び表示されます。

about.htmlテンプレートを編集して同じものを使用することもできます。

<!-- djangotemplates/example/templates/about.html -->

{% extends 'base.html' %} <!-- Add this for inheritance -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}About Us {% endblock %}</title>
</head>
<body>
  {% block pagecontent %}
    <p>
    We are a group of Django enthusiasts with the following idiosyncrasies:

    <ol>
        <li>We only eat bananas on Saturdays.</li>
        <li>We love making playing football on rainy days.</li>
    </ol>
    </p>
    <a href="{% url 'home' %}">Go Home</a>
    <a href="{% url 'about' %}">About This Site</a>
  {% endblock %}
</body>
</html>

これで、[バージョン情報]ページに次のように表示されます:

これは以前とまったく同じです!

ただし、両方のテンプレートがベーステンプレートを継承しているため、簡単にスタイルを設定できます。 cssフォルダーでmain.cssを開き、次のスタイルを追加します。

.container {
    background: #eac656;
    margin: 10 10 10 10;
    border: 3px solid black;
}

これにより、コンテンツをロードするコンテナdivのスタイルが設定されます。 ブラウザを更新します。 あなたはこれを見るはずです:

ホームページ:

アバウトページ:

ビューからのデータを使用したテンプレートのレンダリング

Djangoのテンプレートエンジンを使用して、非常に強力な方法でデータを表示できます。 このセクションでは、データをテンプレートに渡すDjangoビューを作成します。 次に、テンプレート内のそのデータにアクセスしてユーザーに表示する方法を説明します。

まず最初に、exampleアプリフォルダーでviews.pyを開きます。 まだ存在しないdata.htmlテンプレートにデータを提供するための新しいビューを追加します。 views.pyファイルを次のように変更します。

# djangotemplates/example/views.py

from django.shortcuts import render
from django.views.generic import TemplateView

class HomePageView(TemplateView):
    template_name = "index.html"

class AboutPageView(TemplateView):
    template_name = "about.html"

# Add this view
class DataPageView(TemplateView):
    def get(self, request, **kwargs):
        # we will pass this context object into the
        # template so that we can access the data
        # list in the template
        context = {
            'data': [
                {
                    'name': 'Celeb 1',
                    'worth': '3567892'
                },
                {
                    'name': 'Celeb 2',
                    'worth': '23000000'
                },
                {
                    'name': 'Celeb 3',
                    'worth': '1000007'
                },
                {
                    'name': 'Celeb 4',
                    'worth': '456789'
                },
                {
                    'name': 'Celeb 5',
                    'worth': '7890000'
                },
                {
                    'name': 'Celeb 6',
                    'worth': '12000456'
                },
                {
                    'name': 'Celeb 7',
                    'worth': '896000'
                },
                {
                    'name': 'Celeb 8',
                    'worth': '670000'
                }
            ]
        }

        return render(request, 'data.html', context)

他のテンプレートのレンダリングに使用したのと同じ種類のビューを使用しています。 ただし、現在、contextオブジェクトをrenderメソッドに渡しています。 コンテキストで定義されたキーと値のペアは、レンダリングされるテンプレートで使用可能になり、他のリストと同じようにそれらを反復処理できます。

これを完了するには、howdyアプリのurls.pyファイルに移動し、次のように新しいビューのURLパターンを追加します。

# djangotemplates/example/urls.py

from django.conf.urls import url
from example import views

urlpatterns = [
    url(r'^$', views.HomePageView.as_view(), name='home'),
    url(r'^about/$', views.AboutPageView.as_view(), name='about'),
    url(r'^data/$', views.DataPageView.as_view(), name='data'),  # Add this URL pattern
]

最後に、テンプレートを作成しましょう。 templatesフォルダーに、data.htmlというファイルを作成し、その中にこのコードを記述します。

<!-- djangotemplates/example/templates/data.html -->

{% extends 'base.html' %}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    {% block pagecontent %}
    <div class="table-div">
    <!-- We will display our data in a normal HTML table using Django's
    template for-loop to generate our table rows for us-->
      <table class="table">
        <thead>
          <tr>
            <th>Celebrity Name</th>
            <th>Net Worth</th>
          </tr>
        </thead>
        <tbody>
          {% for celebrity in data %}
            <tr>
              <td>{{ celebrity.name }}</td>
              <td>{{ celebrity.worth }}</td>
            </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
    {% endblock %}
  </body>
</html>

data.htmlでは、基本的にforループであるものを使用してデータリストを調べていることがわかります。 Djangoテンプレートの値のバインドは、AngularJSの場合と同様に、{{}}中括弧を使用して行われます。

サーバーが稼働している状態で、http://localhost:8000/data/に移動してテンプレートを表示します。

テンプレートにスニペットを含める

これで、index.htmlabout.htmldata.htmlの3つのテンプレートができました。 簡単なナビゲーションバーを使用して、それらをリンクしましょう。 まず、ナビゲーションバーのコードを別のHTMLテンプレートに記述しましょう。

exampleアプリ内のテンプレートフォルダーに、partialsという名前の新しいフォルダーを作成します。 その中に、nav-bar.htmlというファイルを作成します。 テンプレートフォルダの構造は次のようになります。

templates
----index.html
----about.html
----data.html
----partials
------nav-bar.html

nav-bar.htmlパーシャルを編集して、次のコードが含まれるようにします。

<!-- djangotemplates/example/templates/partials/nav-bar.html -->

<div class="nav">
  <a href="{% url 'home' %}">Go Home</a>
  <a href="{% url 'about' %}">About This Site</a>
  <a href="{% url 'data' %}">View Data</a>
</div>

テンプレートにスニペットを含めるのは非常に簡単です。 Djangoのテンプレートエンジンによって提供されるincludesキーワードを使用します。 先に進み、index.htmlを次のように変更します。

<!-- djangotemplates/example/templates/index.html -->

{% extends 'base.html' %}

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>{% block title %}Welcome Home {% endblock %}</title>
</head>
<body>
  {% block pagecontent %}
    <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
      Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
      Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
      Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    </p>
    {% include 'partials/nav-bar.html' %} <!--Add this-->

    <!-- Remove these two lines -- >
    <!-- <a href="{% url 'home' %}">Go Home</a> -->
    <!-- <a href="{% url 'about' %}">About This Site</a> -->
  {% endblock %}
</body>
</html>

about.htmlを次のように変更します。

<!-- djangotemplates/example/templates/about.html -->

{% extends 'base.html' %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}About Us {% endblock %}</title>
</head>
<body>
  {% block pagecontent %}
    <p>
    We are a group of Django enthusiasts with the following idiosyncrasies:

    <ol>
        <li>We only eat bananas on Saturdays.</li>
        <li>We love making playing football on rainy days.</li>
    </ol>
    </p>
    {% include 'partials/nav-bar.html' %} <!--Add this-->

    <!-- Remove these two lines -- >
    <!-- <a href="{% url 'home' %}">Go Home</a> -->
    <!-- <a href="{% url 'about' %}">About This Site</a> -->
  {% endblock %}
</body>
</html>

最後に、data.htmlを次のように変更します。

<!-- djangotemplates/example/templates/data.html -->

{% extends 'base.html' %}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    {% block pagecontent %}
    <div class="table-div">
      <table class="table">
        <thead>
          <tr>
            <th>Celebrity Name</th>
            <th>Net Worth</th>
          </tr>
        </thead>
        <tbody>
          {% for celebrity in data %}
            <tr>
              <td>{{ celebrity.name }}</td>
              <td>{{ celebrity.worth }}</td>
            </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
    {% include 'partials/nav-bar.html' %} <!--Add this-->
    {% endblock %}
  </body>
</html>

私たちの仕事をチェックする時が来ました! ブラウザを開き、http://localhost:8000に移動します。 これが表示されるはずです:

すべてのページがナビゲーションバーにリンクされているため、最小限のコードを記述して、ページ間を簡単に行き来できます。 data.htmlテンプレートは次のとおりです:

そしてここにabout.htmlがあります:

注:ナビゲーションバーのリンクをスタイル設定するために、次のCSSを追加しました。 自由に使用するか、独自のスタイルで遊んでください。

// djangtotemplates/static/css/main.css

.container {
    background: #eac656;
    margin: 10 10 10 10;
    border: 3px solid black;
}

.nav a {
    background: #dedede;
}

フィルタ

フィルタは、パイプされたデータを取得し、フォーマットされた方法で出力します。 Djangoテンプレートは、humanizeフィルターのコレクションにアクセスできます。これにより、データがより人間に読めるようになります。 これらのフィルターのいくつかを使用して、データテンプレート内の有名人の純資産フィールドを読みやすくしましょう。

Djangoのヒューマナイズフィルターを使用するには、最初にいくつかの設定を編集する必要があります。 djangotemplates/settings.pyを開き、INSTALLED_APPSリストを次のように編集します。

# djangotemplates/djangotemplates/settings.py

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize', # Add this line. Don't forget the trailing comma
    'example',
]

これで、テンプレートでフィルターを使用できます。 intcommaフィルターを使用して、カンマを多数追加し、読みやすくします。 data.htmlを次のように変更してみましょう。

<!-- djangotemplates/example/templates/data.html -->

{% extends 'base.html' %}
{% load humanize %} <!-- Add this-->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    {% block pagecontent %}
    <div class="table-div">
      <table class="table">
        <thead>
          <tr>
            <th>Celebrity Name</th>
            <th>Net Worth</th>
          </tr>
        </thead>
        <tbody>
          {% for celebrity in data %}
            <tr>
              <td>{{ celebrity.name }}</td>
              <td>$ {{ celebrity.worth | intcomma }}</td> <!--Modify this line-->
            </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
    {% include 'partials/nav-bar.html' %}
    {% endblock %}
  </body>
</html>

http://localhost:8000/data/に移動すると、純資産値のよりわかりやすいリストが表示されます:

humanizeパッケージにはさらに多くのフィルターが含まれています。 それらについて読むここ

静的ファイルの収集

静的ファイルの収集について話したことを覚えていますか? 次のコマンドを試してください。

python manage.py collectstatic

次のようなプロンプトが表示されます。

You have requested to collect static files at the destination
location as specified in your settings:

      /Users/amos/projects/djangotemplates/staticfiles

This will overwrite existing files!
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel:

先に進み、yesと言います。

このコマンドは、Djangoにすべてのプロジェクトフォルダーを調べ、すべての静的ファイルを探して、それらを1つの場所(設定で定義した静的ルート)に保存するように指示します。 これは、特にサイトを本番環境に展開する場合に非常に効率的です。

コマンドcollectstaticを実行すると、プロジェクトフォルダーのルートにstaticfilesという名前の新しいフォルダーが作成されます。 プロジェクトのsettings.pyファイルの静的ルート設定を編集することにより、この場所を別の場所に変更できます。 これらのstaticfilesを使用するには、テンプレートでload staticの代わりにload staticfilesと言います。 それ以外はすべて、前のstaticフォルダーを使用した場合と同じです。

結論

このチュートリアルの最後に到達しました。おめでとうございます。 これで、Djangoテンプレートがどのように機能するかをより詳細に理解できるはずです。 より深い情報が必要な場合は、ドキュメントが友達であることを忘れないでください。 このチュートリアルの完全なコードはここにあります。 以下のコメントに、考え、質問、懸念事項を残してください。