apache服务器无法在Django项目中找到静态文件

时间:2013-04-23 20:30:40

标签: django apache mod-python django-staticfiles django-static

我正在尝试使用mod_python在apache服务器上上传我的代码。我已经尝试了很多,但服务器无法访问我的静态文件(我的所有图像,js和css)。 以下是我的虚拟主机设置:

<VirtualHost *:80>
ServerName mysite.com
ServerAlias www.mysite.com
Alias /static/ /home/mysite/products/static/
#
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.mysite\.com
RewriteRule (.*) http://mysite.com$1 [R=301,L] 
#
DocumentRoot /home
<Directory /home/mysite/>
    SetHandler mod_python
    PythonHandler mod_python.publisher
    PythonDebug On
</Directory>
<Directory />
    Options FollowSymLinks
    AllowOverride None
</Directory>

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
    AllowOverride None
    Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
    Order allow,deny
    Allow from all
</Directory>

ErrorLog /var/log/apache2/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog /var/log/apache2/access.log combined

</VirtualHost>

我的访问日志:

"GET /giftproducts/static/js/top.js HTTP/1.1" 404 1487 "http://xxx.xxx.xx.xxx/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31"
xxx.xxx.xx.xxx - - [23/Apr/2013:15:09:52 -0500] "GET /giftproducts/static/css/index.css HTTP/1.1" 404 1486 "http://xxx.xxx.xx.xxx/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31"

(404页未找到 - 为什么!?)

settings.py:

import os
import sys
path = os.path.abspath(os.path.join(os.path.dirname(__file__)))
MEDIA_ROOT = path + '/products/media/'
MEDIA_URL = '/media/'

PROJECT_ROOT = path
STATIC_ROOT = path + '/products/static/'
STATIC_URL = '/products/static/'

STATICFILES_DIRS = (
    path,

)

STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
TEMPLATE_DIRS = (
path + '/products/templates',
) #this works, since it is loading the html

尝试提供类似“/ static / x”和“{{STATIC_URL}} x”的路径,但没有任何效果。

对此的任何帮助都会很棒。感谢。

更新:除了Glyn在下面建议的内容之外,我将这些行添加到我的urls.py中,然后它才有效。

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

1 个答案:

答案 0 :(得分:3)

1)您是否在虚拟主机中正确设置了静态文件?我没有看到他们......

    Alias /media/ /products/static
    Alias /static/ /products/static


    <Directory /products/static>
        Order allow,deny
        Allow from all
    </Directory>

2)在模板中始终使用 {{ STATIC_URL }}来检索静态文件,这是最佳做法。

3)添加django.contrib.staticfiles并运行collectstatic management command