【问题标题】:Django css static not loadDjango css静态不加载
【发布时间】:2018-02-03 11:08:00
【问题描述】:

CSS 没有加载!!我已经阅读了一些类似的问题,但我无法解决这个问题。为什么我错了?

静态目录路径:

/project/static

settings.py

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

base.html

<!DOCTYPE html>
{% load static %}

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}">
<title>title</title>
</head>
<body
{% block content %}
{% endblock content %}
</body>
</html>

【问题讨论】:

  • 您能否检查您的控制台以查看您是否遇到任何网络错误?特别是 404,这将使您了解它试图从哪个 URL 加载 CSS。您还可以检查页面上呈现的内容是否符合您的预期。

标签: django


【解决方案1】:

根据文档,你可以这样尝试

settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/var/www/static/',# Here you can mention your static directory
]

urls.py

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


urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

在您的模板中

{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image"/>

将您的静态文件存储在应用中名为 static 的文件夹中。例如 my_app/static/my_app/example.jpg

【讨论】:

    【解决方案2】:

    也可以在 settings.py 中试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-31
      • 2017-10-08
      • 2011-11-26
      • 2012-10-03
      • 1970-01-01
      • 2016-09-29
      • 2017-04-08
      相关资源
      最近更新 更多