Django:无法加载/ static中的CSS文件

时间:2019-04-16 13:41:00

标签: css django static

自从完成Django网站的后端以来,我就开始添加一些样式。 显示了我的html文件,但似乎没有CSS链接到它们,但是当我在Firefox中显示源代码时,路径是正确的。

mywebsite/
----blog/
----mywebsite/
----static/
--------css/
------------struct.css
----templates/
--------layouts/
--------errors/
------------404.html
--------html/
------------struct.html

Django版本:2.1.7

settings.py:

DEBUG = False
ALLOWED_HOSTS = ['*']

INSTALLED_APPS = [
    # other apps...
    'django.contrib.staticfiles',
]

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

urls.py:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

struct.html:

{% load static %}

<!DOCTYPE html>
<html lang="en" dir="ltr">

  <head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width; initial-scale=1.0;">

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

    <title>test</title>

  </head>

  <body>

    <p>test</p>


  </body>

</html>

struct.css:

p{
    color:red:
}
body{
    background-color:black:
}

2 个答案:

答案 0 :(得分:1)

通常,静态文件路径应类似于此appname / static / appname / yourfiles 无需更改网址格式。

假设您的应用程序名称为Myapp,则CSS文件的正确路径为

Myapp / static / Myapp / css / struct.css

要包括静态文件,请在settings.py中添加以下行

STATIC_URL = '/static/'

以及您的html模板

<!doctype html>
{% load static %}
<link rel="stylesheet" href="{% static 'Myapp/css/struct.css' %}">

如果您在应用程序中包含静态文件,则无需使用

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

您可以在Django文档中参考Managing Static Files

如果您设置DEBUG = False,那么您必须遵循https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

答案 1 :(得分:0)

在settings.py

中定义静态根
STATIC_ROOT = BASE_DIR + '/static/'

希望有帮助

推荐this