Django静态文件 - CSS无法正常工作

时间:2012-10-16 15:53:48

标签: python django django-urls static-files

  

可能重复:
  Django and Serving Static Files

我在base.html上加载CSS有一个问题。我把所有的css文件放在/ static目录下。

urls.py我输入了以下代码:

if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$', 'django.views.static.serve',
           { 'document_root': '/home/bkcherry/botstore/botstore/static' }),
    )

在base.html,我提出以下内容:

<link rel="Stylesheet" type="text/css" href="/static/css.css" />

当我转到main.html时,css样式无效。我需要配置settings.py MEDIA_ROOTMEDIA_URLSTATIC_ROOT

3 个答案:

答案 0 :(得分:1)

您必须使用MEDIA_ROOT或MEDIA_URL这适用于上传的媒体而不是您的静态内容,并且您不需要设置网址格式,因为这仅适用于django 1.2或“如果您使用的是用于本地开发的其他服务器“:https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-in-development

您需要将静态文件放入: botstore / botstore /静态/ botstore / css.css

然后使用:

HOME_ROOT = 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 = os.path.join(HOME_ROOT, 'staticfiles')

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

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

然后在您的HTML中,您可以参考您的静态文件:

<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}botstore/css.css" />

答案 1 :(得分:0)

我认为你的路径末尾需要一个斜杠,即'/home/bkcherry/botstore/botstore/static/'

答案 2 :(得分:0)

如果您查看官方文档

from django.conf import settings

# ... the rest of your URLconf goes here ...

if settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
            'document_root': settings.MEDIA_ROOT,
        }),
    )

MEDIA_ROOT应该/在最后(https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-MEDIA_ROOT