django won't load staticfiles from statifiles_dirs

三世轮回 提交于 2020-03-05 05:49:45

问题


My style.css is placed in appname/static/appname/.

My settings.py has this code:

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static/"),
    )

And in my base.html I load it like this:

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'appname/style.css' %}">

But the styles are not loading. If I remove STATICFILES_DIRS and change STATIC_URL = '/static/' to STATIC_URL = '/static/appname/', it works perfectly, but I guess it's not the best practice for the case I'll add any other app to the project later. What I might be doing wrong?


回答1:


Just change one thing,

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

It will search in static folder inside your app. Also if you want to add a specific directory,

STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"), '/your specific directory/',
)

From here you can directly add the particular file name, and djnago will search in that specific directory.




回答2:


Remove "appname" in {% static 'appname/style.css' %}, you must not place it there because python knows automatically in which application the file is, it get the application name from the request




回答3:


By default django picks static directory from app's directory. So, if your static directory is inside app directory there is no need to specify STATICFILES_DIRS. Now /static/ will point to files and directories in the static directory of your app. To refer your css file use

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'appname/style.css' %}">


来源:https://stackoverflow.com/questions/52403518/django-wont-load-staticfiles-from-statifiles-dirs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!