5

可能重复:
如何在 Django 项目/应用程序中组织和加载 CSS?

我关注了几个关于如何在 Django 中设置静态文件的网站。这是我的步骤。

配置setting.py:

STATIC_ROOT = '/Users/kin/mysite/static'
STATIC_URL = '/static/'

运行 collectstatic 命令:

python manage.py collectstatic

之后,我看到我的图像文件被复制到了 STATIC_ROOT。

然后在我的模板中,我尝试通过以下方式使用我的图像文件:

<img border="0" src="{{ STATIC_URL }}images.jpg" width="304" height="228">

但是当我在浏览器上加载它时没有图像。我检查了页面源并且 STATIC_URL 似乎是空的。

任何人都可以在这里阐明一下吗?

谢谢

4

4 回答 4

5

不要在您的设置中硬编码路径。我通常把我的静态文件放在我的主项目中,所以我的设置文件看起来像这样

import os
MAIN_PROJECT = os.path.dirname(__file__)

然后

# 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: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(MAIN_PROJECT, 'static/'),
)

之后,您可以{{ STATIC_URL }}在您的视图中使用

于 2013-01-22T07:40:33.483 回答
4

实际上我只是使用以下代码就对了:

{% load staticfiles %}
<img border="0" src="{% static 'image.jpg' %}" width="304" height="228">

这会将 STATIC_URL 路径呈现给我。

谢谢大家帮助我!

于 2013-01-22T07:43:28.673 回答
1

如果您正在运行您的应用程序,python manage.py runserver那么您可能需要将以下内容添加到您的 url conf 的末尾(请参阅docs)。

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns += staticfiles_urlpatterns()

使用 django 的开发服务器提供静态文件的过程与使用生产 Web 服务器的过程不同。

于 2013-01-22T07:30:35.733 回答
0

你可以试试这个

导入设置urls.py 并将以下代码粘贴到您的 urls.py

if settings.DEBUG:
    urlpatterns += patterns('django.views.static',
    (r'^static_media/(?P<path>.*)$', 
        'serve', {
        'document_root': 'path/to/your/static/folder',
        'show_indexes': True }),)

现在转到您的 settings.py 并更改设置,例如

MEDIA_URL = '/static_media/'

# 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: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

现在访问您的静态文件,例如

<link rel="stylesheet" type="text/css" href="{{MEDIA_URL}}css/header.css" />
于 2013-01-22T07:34:56.133 回答