如何在Django中设置静态文件

时间:2013-01-22 07:10:45

标签: django static

  

可能重复:
  How to organize and load CSS within Django project/app?

我已经关注了几个关于如何在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 个答案:

答案 0 :(得分:4)

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

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 }}

答案 1 :(得分:3)

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

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

这将向我呈现STATIC_URL路径。

感谢所有人帮助我!

答案 2 :(得分:1)

如果您使用python manage.py runserver运行应用,则可能需要在网址配置的末尾添加以下内容(请参阅docs)。

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns += staticfiles_urlpatterns()

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

答案 3 :(得分: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" />