【问题标题】:Having trouble displaying static files无法显示静态文件
【发布时间】:2013-10-26 19:42:02
【问题描述】:

我无法弄清楚如果我应该将任何 url 内容添加到我的 urls.py 文件中以能够显示静态文件。我已经尝试添加以下内容,因为我已经看到它在堆栈溢出时对其他人有用

url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': True }),

url(r'', include('django.contrib.staticfiles.urls')),

static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

这些似乎都不起作用。

我似乎在工作。

【问题讨论】:

    标签: python django python-2.7 django-1.5


    【解决方案1】:

    您不需要在 urls.py 文件中包含静态。在您的 settings.py 中,您必须使用静态文件和 url 指定目录:

    # Absolute path to the directory static files should be collected to.
    # Don't put anything in this directory yourself; store your static files
    # in apps' "static/" subdirectories and in STATICFILES_DIRS.
    # Example: "/var/www/example.com/static/"
    STATIC_ROOT = ''
    
    # URL prefix for static files.
    # Example: "http://example.com/static/", "http://static.example.com/"
    STATIC_URL = '/static/'
    

    【讨论】:

    • 是我唯一需要指定 URL 的地方吗?因为我仍然无法在 /admin 页面和其他页面(我的所有页面)上显示静态文件。
    • 是的,它是唯一指定 URL 的地方。此外,当您在生产中时,您必须运行“python manage.py collectstatic”命令,该命令会将所有静态内容从您的应用程序复制到 STATIC_ROOT 中指定的路径。
    • 虽然我需要记住有用的信息,但我仍然无法显示我的静态文件。
    • 这不会发生在任何模板上,它发生在我的所有模板中,包括默认的管理页面。
    【解决方案2】:

    尝试跑步,

    python manage.py collectstatic
    

    再试一次,你不需要在 urls add 中添加任何东西

    STATIC_URL = '/static/'
    

    在setting.py中

    在你的应用目录中创建一个名为 static 的文件夹

    将您的静态文件放在该目录中

    用于例如<img src="{% static '<path from static directory>' %}" />

    不要忘记在模板顶部包含{% load staticfiles %}

    【讨论】:

    • <path to your file from>/static/ 中我的文件的路径,对吗?
    • 我认为它会修复它,因为我忽略了添加标签{% load staticfiles %},但它没有,我仍然无法显示静态文件。
    • 您是否在已安装应用的 settings.py 文件中添加了该应用
    • 是的,我做到了,我的管理员静态文件也不起作用
    • 你在尝试这个吗? ,在您的本地或生产中
    猜你喜欢
    • 2016-03-12
    • 1970-01-01
    • 2018-08-28
    • 2021-05-30
    • 2017-05-12
    • 1970-01-01
    • 2014-12-06
    • 2020-06-21
    • 1970-01-01
    相关资源
    最近更新 更多