【问题标题】:Django static page not found 404找不到 Django 静态页面 404
【发布时间】:2018-05-25 03:56:12
【问题描述】:

Django css 文件未找到错误,加载 css 文件失败,获取 404 文件未找到错误 也 **我收到另一个错误:

不允许加载本地资源。

是的,我试过 c:/path/chrome.exe -,它所做的只是启动一个浏览器,并没有将我导航到任何url/website。

你们的建议,这是我的代码。我将只发布我认为相关的代码。我的 Django 版本是最新的,2。

浏览器浏览器

GET http://127.0.0.1:8000/static/care/style.css 404 (Not Found)

settings.py

# Application definition

INSTALLED_APPS = [
    'care.apps.CareConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]


# SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'

style.css 存在于目录 Care 中,该目录存在于另一个名为 static 的目录中。

我尝试使用相对路径和“绝对路径”,当我尝试使用绝对路径时,我得到一个不同的错误

不允许加载本地资源。

为了通过,我实际上从 HTML 源代码中复制了链接并将其粘贴到浏览器中,它确实将我带到了 style.css 文件。路径没有任何问题。

为什么 Django 没有检测到 css 文件?我在 Firefox 浏览器中也面临同样的问题,只是它不像 Chrome 那样列出错误

index.html

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

【问题讨论】:

  • 你是否已经完成了这里解释的所有事情,包括urls.py? docs.djangoproject.com/en/2.0/howto/static-files/…
  • 问候塞尔丘克,是的,我刚刚做了,仍然遇到同样的错误,无法检测到 css 文件。我按照您的建议将其添加到 urls.py"+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)" ,但它不起作用:(

标签: python django python-3.x


【解决方案1】:

如果你的MEDIA_URL被定义为/media/,你可以通过在你的APP urls.py中加入下面的sn-p来做到这一点:

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

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  1. 将 STATIC_ROOT 设置设置为您要从中提供这些文件的目录,例如:

    STATIC_ROOT = "/var/www/example.com/static/"

运行collectstatic管理命令:

$ python manage.py collectstatic

这会将静态文件夹中的所有文件复制到STATIC_ROOT 目录中。

【讨论】:

    猜你喜欢
    • 2014-07-20
    • 2016-08-01
    • 2016-08-01
    • 2015-10-22
    • 2014-03-20
    • 2020-10-27
    • 2019-07-21
    • 1970-01-01
    • 2019-01-12
    相关资源
    最近更新 更多