python - 在Django 1.8中,如何设置settings.py以便管理静态文件?

标签 python django twitter-bootstrap

settings.py 中管理静态文件的代码片段如下。

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATICFILES_DIRS = [
    os.path.join(
        os.path.dirname(__file__),
        'static',
    ),
]
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            BASE_DIR + '/templates/'
        ],
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            'loaders': [
                ('django.template.loaders.cached.Loader', [
                    'django.template.loaders.filesystem.Loader',
                    'django.template.loaders.app_directories.Loader',
                ]),
            ],
            'debug' : True
        },
    },
]
STATIC_URL = '/static/'

url.py文件如下。

from django.conf.urls import include, url
from django.contrib import admin
from tweets.views import Index, Profile
admin.autodiscover()

urlpatterns = [
    url(r'^$', Index.as_view()),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^user/(\w+)/$', Profile.as_view()),
]

views.py文件如下

{% load staticfiles %}
<html>
<head>
    <title>Django</title>
    <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}" media="screen">
</head>
<body>
    {% block content %}
    <h1 class="text-info">Hello {{name}}!</h1>
    {% endblock %}
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
</body>
</html>

当我运行服务器时,浏览器找不到bootstrap.min.js文件。

Page not found at /static/bootstrap/css/bootstrap.min.css http://localhost:8000/static/bootstrap/css/bootstrap.min.css 'bootstrap/css/bootstrap.min.css' could not be found

看来静态文件 url 是正确的。 但浏览器找不到静态文件。 请告诉我原因以及如何处理?

最佳答案

提供静态文件 during development您应该将以下代码添加到 urls.py 中:

from django.conf.urls import include, url
from django.contrib import admin
from tweets.views import Index, Profile
from django.conf import settings
from django.conf.urls.static import static
admin.autodiscover()

urlpatterns = [
    url(r'^$', Index.as_view()),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^user/(\w+)/$', Profile.as_view()),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

您应该在项目文件夹中创建路径static/your_app/your_files

关于python - 在Django 1.8中,如何设置settings.py以便管理静态文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44032713/

相关文章:

python - Pygame 简单程序测试显示卡住

python - Django 分页不起作用

html - 列在窗口调整大小时显示为行

python - 一次获取 NumPy 数组中多个元素的索引(可以重复)

注销后在请求方法中添加 Django/Vue 大括号

python - 我可以采取什么措施来保护我的 django 站点的源代码不被他人看到?

python - 如何提高 django mysql 复制性能?

javascript - 滚动时更改固定标题

html - 需要有关 Bootstrap Pull Push 问题的帮助

python - 平铺固定大小的矩形以覆盖给定的点集