静态CSS文件未在Django框架中加载

时间:2017-01-07 19:16:45

标签: python django python-2.7 static django-templates

我在localhost上运行但样式表无效

这是我的项目设置:

-main
   -main
   -home
      -templates
         -home
             -index.html
   -static
      -css
         -style.css

我的settings.py:

STATICFILES_DIRS = [
    "/static/",
]

STATIC_URL = '/static/'

的index.html:

{% load staticfiles %}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
    <title>My Home Page</title>
    <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" />
</head>
<body>
<p>My Content</p>
</body>
</html>

以下是我的服务器输出的内容:"GET /static/css/style.css HTTP/1.1" 404 1652

有什么问题?

5 个答案:

答案 0 :(得分:1)

设置为STATICFILES_DIRS,而不是STATICFILES_DIR。

答案 1 :(得分:0)

好的,这个改变似乎解决了这个问题:

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

答案 2 :(得分:0)

index.html应该是这样的:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
{% load staticfiles %}
<html lang="en">
<head>
    <title>My Home Page</title>
    <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" />
</head>
<body>
    <p>My Content</p>
</body>
</html>

答案 3 :(得分:0)

STATICFILES_DIRS = [     os.path.join(BASE_DIR,“静态”),]

会起作用!

答案 4 :(得分:0)

我遇到了同样的问题,因为我在 Django 中的设置文件没有以下代码行,我添加了这些代码来解决问题

STATICFILES_DIRS = [
    BASE_DIR / "static",
    '/var/www/static/',
]

在此处查看静态文件文档:https://docs.djangoproject.com/en/3.1/howto/static-files/