Djangoテンプレートと静的ファイルの操作
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
という新しいフォルダーが作成されます。
cd
をdjangotemplates
に。
これで、フォルダ構造は次のようになります。
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.html
とabout.html
の2つのテンプレートが含まれています。
これらのテンプレートの両方にCSSを含める必要があります。 両方で同じコードを書き直す代わりに、Djangoでは両方が継承するベーステンプレートを作成できます。 これにより、共有されているものを変更する必要があるときに、テンプレートに多くの繰り返しコードを記述する必要がなくなります。
それでは、ベーステンプレートを作成しましょう。 djangotemplates/example/templates
にbase.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.html
、about.html
、data.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テンプレートがどのように機能するかをより詳細に理解できるはずです。 より深い情報が必要な場合は、ドキュメントが友達であることを忘れないでください。 このチュートリアルの完全なコードはここにあります。 以下のコメントに、考え、質問、懸念事項を残してください。