LoginSignup
15
9

More than 1 year has passed since last update.

debug=Falseとした場合でもDjangoに静的ファイルを参照させる

Last updated at Posted at 2021-06-19

はじめに

Djangoでは settings.py で debug=False とした時、各アプリケーションフォルダの下にある static フォルダの画像やCSSが参照されなくなる仕様である。

debug=False、つまり本番環境の場合は python manage.py collectstatic コマンドで、各アプリの static をフォルダのファイルを1つのフォルダに集め、そのフォルダをWEBサーバで配信する設定とするのが定石のようである。

しかしながら、この状態で WEBサーバを使わずに django の manage.py で起動した場合、集めた static フォルダのファイルは引き続き参照されない

開発中は、manage.py で本番設定の動きを確認したい こともあるのでこれは不便だ。

状況の説明が長くなってしまったが本記事はこれを回避するものである。

環境

  • python 3.8
  • Django 3.0

方法

manage.py と同じフォルダに、各アプリケーションのフォルダの下の静的ファイルを集めた static フォルダがあるという前提で話を進める。

対応方法として、 URLのパス /static/ に対し static フォルダを表示するよう設定すればよい。

具体的には、urls.py に対し以下のように re_path(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),を入れてあげればよい。

プロジェクトのurls.py

from django.contrib import admin
from django.urls import path, include, re_path
from django.conf import settings
from django.views.static import serve 

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include("myqsar_app.urls")),
    re_path(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}), 
]

参考

15
9
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
15
9