【问题标题】:Serving Static File on Django在 Django 上提供静态文件
【发布时间】:2019-10-03 06:23:18
【问题描述】:

我一直试图在我的 Django 项目中提供我的静态文件,但是它找不到或加载它。我尝试了不同的方法,但似乎都无法解决问题。

静态文件夹与 manage.py 位于同一目录中。

另外,我已经安装了WitheNoise,但也没有解决问题。

另外:我正在使用docker,我已经完成了收集静态并检查了容器。所有文件都正确存在。

Django 版本 = 2.0.1

开发环境

代码结构:

项目

- assets
- config
- docs
- project-root
- - static
- - manage.py
- - templates
- - apps
- - project-root
- - - settings.py
- - - urls.py
...
...

setting.py

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

STATIC_URL = '/static/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

html文件

{% load static %}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <!-- Bootstrap -->
  <link rel="stylesheet" href="{% static "css/bootstrap.css" %}">
  <link rel="stylesheet" href="{% static "css/jquery.bxslider.css" %}">
  <!-- Custom -->
  <link rel="stylesheet" href="{% static "css/style.css" %}">
  <link rel="stylesheet" href="{% static "css/animate.css" %}">

</head>

如果我需要在帖子中添加对您有所帮助的其他内容,请告诉我。 谢谢,

【问题讨论】:

标签: python django static


【解决方案1】:

问题中没有提到Django的版本,还有环境-(生产/开发)

-在最近的python版本中推荐使用{% load static %}而不是{% load staticfiles %}

-如果Debug is Truedjango.contrib.staticfiles 不在INSTALLED_APP 中-

-将django.contrib.staticfiles 添加到INSTALLED_APP 或者 将static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) 附加到urlpatterns 以提供静态文件。

  • 对于不在应用文件夹中的静态文件,该目录需要在 STATICFILES_DIRS 中列出-
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    'any_other_locations',
]

【讨论】:

  • 感谢您的帮助。但它并没有解决问题,它仍然找不到文件......我编辑了这个问题,提供了有关结构和版本的更多信息
【解决方案2】:

编辑您的 settings.py 文件并将 WhiteNoise 添加到 MIDDLEWARE 列表。 WhiteNoise 中间件应该直接放在 Django SecurityMiddleware 之后(如果你正在使用它)和所有其他中间件之前。

MIDDLEWARE = [
  'django.middleware.security.SecurityMiddleware',
  'whitenoise.middleware.WhiteNoiseMiddleware',
  #(Rest of the Middleware here)
]

白噪声缓存和静态文件的路由:

STATIC_URL = '/static/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

然后运行 ​​collectstatic

django-admin collectstatic

python3 manage.py collecstatic

如果你想在 docker 容器中运行,这里有更多信息

https://docs.docker.com/engine/reference/commandline/exec/

有关 Whitenoise 的更多信息:

http://whitenoise.evans.io/en/stable/django.html#

【讨论】:

  • 感谢您的评论。即使进行了更改,我仍然无法找到文件。错误仍然存​​在...我用有关版本和结构的更多信息编辑了我的问题
  • 嗯,试图记住我用来使它在我的项目中工作的东西。您是否也在settings.py 中启用了白噪声?请参阅:Enable Whitenoise Middleware