【问题标题】:Django doesn't see static filesDjango 看不到静态文件
【发布时间】:2019-03-31 14:28:15
【问题描述】:

所以问题是 django 根本无法识别静态文件。无论我尝试过什么,它都不起作用。我尝试将全局搜索方式更改为 css 文件的直接 url,这似乎都不起作用。

我的项目结构如下:

这是我的代码:

DEBUG = True
INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
]
    STATIC_URL = '/static/'
    STATIC_DIRS = [os.path.join(BASE_DIR, "static")]
    STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn")
    from django.contrib import admin
    from django.urls import path
    from something.views import *
    from django.conf import settings
    from django.conf.urls.static import static
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', home),
        ]
    if settings.DEBUG:
        urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
    {% load static from staticfiles %}
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <title>Monkeys</title>
            <link rel="stylesheet" type="text/css" href="{% static 'css/file.css' %}"/>
        </head>

可以在互联网上的任何主题中找到答案,所以我希望你能提供帮助。

【问题讨论】:

  • 欢迎来到 StackOverflow!你跑python manage.py collectstatic了吗?此外,问题是在调试模式还是实时模式(或两者)中出现?
  • 是的,应该如此
  • 据我所知,您已经收集了静态文件。
  • 请从渲染页面发布生成的文件 url,尝试手动打开它并发布它会返回的错误消息/http 状态。还有print(STATIC_ROOT).
  • 显示此文件的完整路径。请回答第一条评论中的问题:您的情况是 DEBUG=False 还是 True?你是在 dev 还是 prod conf 上运行?

标签: python django


【解决方案1】:

Go some steps back and set up static files and make sure it follows exactly django docs

Only about static files

This project has similar structure as yours

当 collectstatic 运行时,默认的 STATICFILES_FINDERS 值 django.contrib.staticfiles.finders.FileSystemFinder 将从 STATICFILES_DIRS 中的任何路径收集您的静态文件。

另一个默认的 STATICFILES_FINDERS 值 django.contrib.staticfiles.finders.AppDirectoriesFinder 将在您的 INSTALLED_APPS 中任何应用的 /static/ 文件夹中查找。

找到的所有静态文件都会放在指定的STATIC_ROOT目录下。

STATIC_URL = '/static/'

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

STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn")

您还可以使用 python manage.py findstatic 查看 collectstatic 将在哪些目录中查找。

manage.py findstatic

【讨论】:

    【解决方案2】:

    目前您有一个错字 - STATIC_DIRS 而不是 STATICFILES_DIRS,因此目前根本没有配置 collectstatic。

    修复它,然后再次运行collectstatic

    【讨论】:

    • 实际上,它指向正确的位置,因为当我尝试您的第二个选项时,它给了我这样的错误 --> FileNotFoundError: [Errno 2] No such file or directory: '/Users /ivanizumov/Desktop/environment/practice/practice/static'
    • 对,我没注意到os.path.dirname。已编辑。
    • 它确实有效,谢谢分配)但是我能再问你一个问题吗?
    猜你喜欢
    • 2022-07-22
    • 2013-05-21
    • 2021-11-25
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多