LoginSignup
0
0

Django学習備忘録 -開発時にCSSをHTMLに反映させる方法-

Posted at

はじめに

Djangoの私的学習メモです。
ChatGPTにて調べた内容と追加で調べた内容、実際に実装した内容を見返せるように記事としてまとめました。

CSSの適用方法(開発時)

開発環境

  • Djnago : 4.2
  • アプリディレクトリ作成済み
  • 各アプリ毎に"static"フォルダを作成しCSSを格納する

手順

  1. "BASE_DIR"のディレクトリを確認
    デフォルトではプロジェクトフォルダが指定されている

    settings.py
    BASE_DIR = Path(__file__).resolve().parent.parent
    
  2. "STATIC_URL"を確認
    デフォルトでは"static/"が指定されている

    settings.py
    STATIC_URL = "static/"
    
  3. "STATICFILES_DIRS"を設定
    "STATICFILES_DIRS"にアプリ毎の静的ファイルのパスを指定する

    settings.py
    STATICFILES_DIRS = [
        BASE_DIR / "アプリ名" / "static",
    ]
    
  4. アプリのディレクトリに"static"ファイルを作成しその中に"css"フォルダを作成

    "プロジェクト名"/
            ├ "プロジェクト名"/
            │        ├ ...
            │        └ settings.py
            ├ "アプリ名"/
            │        ├ ...
            │        └ static/
            │                └ css/
            ├ templates/
            ├ db.sqlite3
            └ manage.py
    
  5. "templates"ディレクトリ内に"アプリ名"ファイルを作成しhtmlを作成
    ここでは例として"index.html"を作成する

        "プロジェクト名"/
            ├ "プロジェクト名"/
            ├ "アプリ名"/
            ├ templates/
            │        └ "アプリ名"/
            │                └ "index.html"
            ├ db.sqlite3
            └ manage.py
    
  6. "css"ファイル内に"index.css"を作成
    ここでは例として"index.css"を作成する

        "プロジェクト名"/
            ├ "プロジェクト名"/
            ├ "アプリ名"/
            │        ├ ...
            │        └ static/
            │                └ css/
            │                    └ index.css
            ├ templates/
            ├ db.sqlite3
            └ manage.py
    
  7. "index.html"のhead内に以下の内容を記載

    • {% load static %}
    • cssのlinkタグ、hrefの参照先はcssファイル内のcssを指定
    index.html
    <!DOCTYPE html>
    <html lang="ja">
      <head>
        {% load static %}   #追加
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" context="IE=edge" />
        <meta name="viewport" context="width=device-width", initial-scale=1.0 />
          <title>Index</title>
        <link rel="stylesheet" href="{% static 'css/index.css' %}" />   #追加
      </head>
    
      <body>
        <h1>index.htmlのh1を表示中</h1>   #必要に応じて記載
      </body>
    </html>
    
  8. "index.css"に任意のコードを記載
    ここでは例としてh1タグの文字の色を変更する

    index.css
    h1 {
        color:darkblue;
    }
    

    文字の色が変わっていれば無事終了です。

まとめ

Djangoでcssを適用させるには"static"フォルダを作成しその中にcssを記載する。
そして、html内で"static"を読み込み、cssのパスを指定することでcssをhtmlに反映させることができる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0