静的ファイル - Django

静的ファイルを保存するディレクトリの作成

hello アプリケーションで扱う静的ファイルは、「 pythonApp/env/djnago_app/hello/static/hello 」に保存します。

CSS を扱うには、「 pythonApp/env/djnago_app/hello/static/hello 」に css ディレクトリを作成し、その中に css ファイルを作成します。

pythonApp/env/djnago_app/hello/static/hello/css/style.css

h1 {
  color: red;
}

次に「 pythonApp/env/djnago_app/hello/templates/hello/index.html 」次のように編集します。

pythonApp/env/djnago_app/hello/templates/hello/index.html

{% load static %}
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="{% static 'hello/css/style.css' %}">
  <title>Document</title>
</head>
<body>
  <h1>hello/index</h1>
  <p><a href="{% url 'sub' %}">hello/sub</a></p>
</body>
</html>

「 settings.py 」で設定する「 static 」ファイルの設定値には以下のようなものがあります。

設定 詳細
STATIC_URL static ファイルの配信用のURL
STATICFILES_DIRS static ファイルのプロジェクト内の保存先
STATIC_ROOT 本番配信用の static ファイルの保存先

Javascript のファイルを読み込む

javascript のファイルを読み込むのも css と同様にします。

pythonApp/env/djnago_app/hello/static/hello/javascripts/script.js

window.onload = function(){
  alert('hello')
}

pythonApp/env/djnago_app/hello/templates/hello/index.html

{% load static %}
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="{% static 'hello/css/style.css' %}">
  <script src="{% static 'hello/javascripts/script.js' %}"></script>
  <title>Document</title>
</head>
<body>
  <h1>hello/index</h1>
  <p><a href="{% url 'sub' %}">hello/sub</a></p>
</body>
</html>