Django网站不加载静态文件

hjqgdpho  于 2022-12-14  发布在  Go
关注(0)|答案(2)|浏览(175)

我正在创建一个django项目,我在项目目录中有模板和静态文件夹。我可以渲染和查看html文件,但是它不能加载存储在静态文件夹中的css文件。我已经在html文件中放置了load static标签,但是当我运行python manage.py runserver时,我得到了这个错误

Performing system checks...

Watching for file changes with StatReloader
System check identified some issues:

WARNINGS:
?: (staticfiles.W004) The directory '/static' in the STATICFILES_DIRS setting does not exist.

System check identified 1 issue (0 silenced).
December 08, 2022 - 14:54:53
Django version 4.1.3, using settings 'brighterstrat.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

这就是我在html文件中引用静态文件的方式

<link rel="stylesheet" href="{% static 'css/bootstrap.min.css'%}">
<link rel="stylesheet" href="{% static 'css/style.css'%}">

setting.py

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [os.path.join(BASE_DIR, '/static')]
STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage"

我怎样才能让它加载css文件

ubof19bj

ubof19bj1#

Django静态可能会让人困惑,主要是因为proddevelopment之间的行为不同(即DEBUG=True
要重述设置:

# Url at which static files are served
# It's the url the browser will fetch to get the static files
# It's prepend to static name by the {% static %} templatetag
STATIC_URL = "static/"

# Directory where static files can be found
# When DEBUG = True, static files will be directly served from there by 
# the manage.py runserver command
STATICFILES_DIRS = [BASE_DIR / "static"]

# Directory to export staticfiles for production
# All files from all STATICFILES_DIRS will be copied by 
# manage.py collectstatic to this directory.
# /!\ It will not be served by django, you have to setup 
# your webserver (or use a third party module) 
# to serve assets from there.
STATIC_ROOT = BASE_DIR / "assets"

在您的示例中,您似乎没有将文件放在STATICFILES_DIRS列出的目录中,因此请确保您有这些文件:

| manage.py (root of your django app)
| static
|   |- css
|   |   |- bootstrap.min.css
|   |   |- style.css
t0ybt7op

t0ybt7op2#

要调试此问题,您可以在设置中添加打印:

print([os.path.join(BASE_DIR, '/static')])

要解决这个问题,您只需要删除斜线,它就可以正常工作。
从os.path.join()文档中:
如果组件是绝对路径,则会丢弃所有先前的组件,并从绝对路径组件继续连接。
这就是BASE_DIR从STATICFILES_DIRS变量中被切断的原因。

相关问题