2012-10-16 251 views
0

可能重複:
Django and Serving Static FilesDjango的靜態文件 - CSS不工作

我有一個問題,在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_ROOT,MEDIA_URLSTATIC_ROOT

+1

如果你只是將瀏覽器指向http://whatever.com/static/css.css,會發生什麼? –

+0

這也有幫助。另外不要錯過通過RequestContext。 http://stackoverflow.com/questions/12819395/how-to-make-my-css-files-to-work-in-django/12821074#12821074 – Thomas

回答

0

我認爲你需要在你的路徑的結尾斜線,即'/home/bkcherry/botstore/botstore/static/'

+0

我把斜槓在MEDIA_ROOT結束,現在它的工作! ! ;) – user1750551

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

+0

Thx所有,它現在工作! ) 我修復代碼在urls.py: 如果settings.DEBUG: urlpatterns的+ =模式( '', URL(R '^靜態/(P *)$',「django的?。 .views.static.serve '{ 'DOCUMENT_ROOT':settings.MEDIA_ROOT, }), ) 而且我配置settings.py: MEDIA_ROOT ='/家/ bkcherry/botstore/botstore /靜態/ ' MEDIA_URL ='/ static /' STATIC_ROOT ='' STATIC_URL ='ht tp:// localhost:8000/static /' 現在GET方法找到了該目錄。 – user1750551

1

你必須而不是使用MEDIA_ROOT或MEDIA_URL這是上傳的媒體,而不是您的靜態內容,並且您不需要設置URL模式,因爲這僅適用於django 1.2或「如果您使用g下地方發展「的一些其他的服務器: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" />