7
6

More than 3 years have passed since last update.

DjangoでCSSを反映させる方法

Posted at

DjangoでCSSを反映させる方法

DjangoでCSSを反映させる方法をご紹介します。

環境

Python 3.7.6
Django 3.0.5

setting.pyの編集

setting.pyの最下部に下記のようなコードを記述します。

setting.py

# 上部省略

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

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    [
        os.path.join(BASE_DIR, "static"), 
    ]
)

CSSファイルの追加

staticフォルダを追加し、下記のような構成にします

| - webproject
| | - setting.py
| | - urls.py
| - webapp
| | - urls.py
| | - views.py
| - templates
| | - form.html
| - static
| | - css
| | | - style.css
|manage.py

HTMLファイルの編集

最上部に{% load static %}を追記します。

{% load static %} 
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>WebApp</title>
    <link href="{% static 'css/style.css' %}" rel="stylesheet">
  </head>
  <body>
    <p>Hello World!</p>
  </body>
</html>

CSSファイルの編集

反映されているか確かめます。

p {
  color: blue;
}

確かに反映されました^_^

スクリーンショット 2020-04-28 21.33.42.png

7
6
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
7
6