2011-05-20 95 views
5

我在Windows XP上運行的Django 1.3,Python 2.7版問題鏈接到靜態文件在Django 1.3

我想設置一個靜態文件夾中的CSS我的Django應用程序。

模板的樣子:

<html> 
    <head> 
     <title>css demo</title> 
     <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/my.css" /> 

    </head> 
    <body> 

生成的HTML看起來像:

<html> 
    <head> 
     <title>css demo</title> 
     <link rel="stylesheet" type="text/css" href="http://localhost/static/css/my.css" /> 

    </head> 
... 

這樣看來,我把一切都建立在以指定的靜態文件模板,然後在生成的html中。

但是在'http://localhost/static/css/my.css'有注意。我如何得到它?

我跑collectstatic像這樣:

C:\root\workspace\mywebapp\src\mywebapp>c:\Python27\python.exe manage.py collectstatic 

You have requested to collect static files at the destination location as specified in your settings file. 

This will overwrite existing files. 
Are you sure you want to do this? 

Type 'yes' to continue, or 'no' to cancel: yes 
Copying 'c:\root\workspace\mywebapp\src\mywebapp\css_demo\static\css\my.css' 

1 static file copied to 'C:/root/workspace/mywebapp/src/mywebapp/static/'. 

所以我現在在C my.css:\ ROOT \工作區\ mywebapp的\ src \ mywebapp \ css_demo \靜\ CSS \ my.css

在我的設置,我有:

STATIC_ROOT = 'C:/root/workspace/mywebapp/src/mywebapp/static/' 
STATIC_URL = 'http://localhost/static/' 

,在我url.py我:

from django.conf.urls.defaults import patterns, include, url 
from django.contrib.staticfiles.urls import staticfiles_urlpatterns 

urlpatterns = patterns('', 

    (r'^mywebapp/', include('mywebapp.css_demo.urls')), 
) 

urlpatterns += staticfiles_urlpatterns() 

所以,如果我理解正確的話,我的CSS爲:

c:\root\workspace\mywebapp\src\mywebapp\css_demo\static\css\my.css 

不應該是位於:

http://localhost/static/css/my.css 

而是我看到:

Page not found (404) 
Request Method: GET 
Request URL: http://localhost/static/css/my.css 
Using the URLconf defined in mywebapp.urls, Django tried these URL patterns, in this order: 
^mywebapp/ 
The current URL, static/css/my.css, didn't match any of these. 

我也試過:

http://localhost/mywebapp/static/css/my.css 
http://localhost/mywebapp/css_demo/static/css/my.css 

我錯過了一步嗎? 有關這方面的文檔有點混亂。 http://docs.djangoproject.com/en/1.3/howto/static-files/ http://docs.djangoproject.com/en/1.3/ref/contrib/staticfiles/

謝謝!

回答

2

我創建了一個文件夾:

C:\root\workspace\mysite\src\mysite\common 

而且在我的設置,我有:

STATIC_ROOT = 'C:/root/workspace/mysite/src/mysite/static/' 
STATIC_URL = '/static/' 
STATICFILES_DIRS = (
    "C:/root/workspace/mysite/src/mysite/common/static", 
) 

這似乎是工作。

5

我敢打賭,你有你的應用程序運行在http://localhost:8000,不http://localhost :)

變化

STATIC_URL = 'http://localhost/static/' 

STATIC_URL = '/static/' 

無需絕對URL那兒。

+0

hmm ...不,我使用runserver在端口80上啓動它0.0.0.0:80 – 2011-05-21 21:45:49

+1

絕對URL並非只是不需要,但根本不起作用。如果你設置STATIC_URL ='http:// localhost:8000/static /',它會產生怪異的錯誤,比如破損的管道和404s的靜態文件。發生這種情況的原因對我來說是未知的,但在https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-in-發展 – 2013-02-28 02:11:02