0
/project_root/
manage.py
    /project/
        /static/
            /css/
            /js/
            /img/
        /media/
        settings.py
        urls.py

这是我的文件夹结构。我的 settings.py 就像:

这是我的settings.py:

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/')

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'staticfiles'),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
 #  'django.contrib.staticfiles.finders.DefaultStorageFinder',
) 

urls.py:

urlpatterns = patterns('',

    url(r'^$', 'employee.views.index'),    
    url(r'^admin/', include(admin.site.urls)),
)+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

urlpatterns += staticfiles_urlpatterns()

模板:

{% load static %}
{% load staticfiles %}

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="{{ STATIC_URL }}img/logo48.png" rel="SHORTCUT ICON" />
<link href="{{ STATIC_URL }}css/master.css" rel="stylesheet" type="text/css" media="screen">
<link href="{{ STATIC_URL }}css/custom.css" rel="stylesheet" type="text/css" media="screen">

在视图源中,我可以看到:

<link href="/static/css/master.css" rel="stylesheet" type="text/css" media="screen">
<link href="/static/css/custom.css" rel="stylesheet" type="text/css" media="screen">
<link href="/static/css/fixes.css" rel="stylesheet" type="text/css" media="screen">

但是我的模板文件中没有加载 css。请指导我。

4

2 回答 2

1

请注意,如果您使用的是内部 django 开发服务器,则此答案不适用。

您是否/static/在 Apache 设置中添加了别名?否则,对该文件夹的任何调用都将导致 404 错误,这意味着您的 CSS 将无法加载。这是我的意思的一个例子:

<VirtualHost *:80>
    ServerName www.example.com
    WSGIScriptAlias / "/path/to/project/project/wsgi.py"

    DocumentRoot "/path/to/project"
    <Directory "/path/to/project">
        <Files wsgi.py>
            Order deny,allow
            Allow from all
        </Files>
    </Directory>

    Alias /media/ "/path/to/project/media/"
    <Directory "/path/to/project/media/">
        Order deny,allow
        Allow from all
    </Directory>

    Alias /static/ "/path/to/project/static/"
    <Directory "/path/to/project/static/">
        Order deny,allow
        Allow from all
    </Directory>
</VirtualHost>
于 2013-09-09T09:05:27.447 回答
0

留空STATIC_ROOT

将其添加到STATICFILES_DIRS

os.path.join(PROJECT_ROOT, 'static/')

确保上面的代码包含:/project_root/project/static

在 urls.py 中删除这些无用的行:

+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

urlpatterns += staticfiles_urlpatterns()

./manage.py collectstatic

应该管用。

编辑:

既然你已经做了{% load static %}你不需要做{{ STATIC_URL }}/..

{% load staticfiles %}
<img src="{% static "my_app/myexample.jpg" %}" alt="My image"/> 

将工作。

于 2013-09-09T08:33:06.767 回答