【问题标题】:Django 1.5.4 unable to serve css on development serverDjango 1.5.4 无法在开发服务器上提供 CSS
【发布时间】:2014-03-17 08:00:36
【问题描述】:

我尝试了很多东西,但无法提供 css 和图像。我正在尝试通过 css 渲染背景图像。以下是代码站点

simple_emp_hr/

 |->hr_base/
 |      |-> views.py
 |      |-> templates/hr_base/homepage.html
 |      |-> static
 |            |->css/base.css
 |            |->images/foto-camion-transformers.jpg
 |
 |->simple_emp_hr/
         |->urls.py
         |->settings.py

以下是视图:

@csrf_protect
def index(request):
    print(request.GET)
    print(request.POST)
    template = loader.get_template('hr_base/homepage.html')
    c = Context()
    c.update(csrf(request))
    c.update({'user':request.user.username})
    str = template.render(c)
    response = str
    print(str)
    hres = HttpResponse()
    hres.write(response)
    return hres

以下是我的urls.py:

from django.conf.urls import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

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

以下是我的settings.py:

# Django settings for simple_emp_hr project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

MANAGERS = ADMINS


ALLOWED_HOSTS = []

SITE_ID = 1

MEDIA_ROOT = ''

MEDIA_URL = ''

STATIC_ROOT = 'static_root/'

STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
"hr_base/static/hr_base/",
)

# 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',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'simple_emp_hr.urls'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
"../simple_emp_hr/hr_base/templates/",
"../simple_emp_hr/emp_users/templates/",
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'hr_base',
)

我的 css 文件有:

body {
    background-image: url ("images/foto-camion-transformers.jpg"); }
title {
    background-color: rgb(238,62,128);
    color: white; }

以下是homepage.html:

<!DOCTYPE html>
<html>
<head>
    <title> Simple Employee HR : Solutions for the companies which are <em>simple</em></title>
    <link href="{{ STATIC_URL }}css/base.css" type="text/css" rel="stylesheet" />
</head>
<body>
    <h1>Simple Employee HR : Solutions for the companies which are <em>simple</em></h1>
    <hr />
    <h2 id="top">Who we are</h2>
    <hr />
    <a href="#top">top</a>
</body>
</html>

视图中的打印允许我打印呈现的 html:

<!DOCTYPE html>
<html>
<head>
    <title> Simple Employee HR : Solutions for the companies which are <em>simple</em></title>
    <link href="css/base.css" type="text/css" rel="stylesheet" />
</head>
<body>
    <h1>Simple Employee HR : Solutions for the companies which are <em>simple</em></h1>
    <hr />
    <h2 id="top">Who we are</h2>
    <hr />
</body>
</html>
[17/Feb/2014 14:40:17] "GET /hr_base/index HTTP/1.1" 200 1455
[17/Feb/2014 14:40:17] "GET /hr_base/css/base.css HTTP/1.1" 404 3640

我从来没有渲染过 css。浏览器显示纯 html 文本。有什么问题? 我是 django 的新手,正在努力学习。我在这里一无所知,无法理解 django 的文档。

编辑: 在遵循 pythonvile 的答案后,我能够让 css 工作,但它仍然很奇怪。 我可以看到效果

h1, h2 {
    color: #ee3e80;}

但是我看不到效果

h1 {
    background-color: rgb(238,62,128);
    color: white; }

body {
    background-image: url ("images/foto-camion-transformers.jpg"); }
title {
    background-color: rgb(238,62,128);
    color: white; }

【问题讨论】:

    标签: python html css django django-templates


    【解决方案1】:

    在定义 MEDIA_ROOT、STATIC_ROOT、STATICFILES_DIRS 和 TEMPLATE_DIRS 时需要使用绝对路径。好的做法是使用以下内容开始设置模块(它不必是单个文件!):

    import os
    PROJECT_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
    

    是的,是的,我知道它的外观,这是迄今为止我遇到的最糟糕的 Python。然而,这是一条路要走。让我们在 shell 中检查一下:

    In [1]: from django.conf import settings
    
    In [2]: settings.PROJECT_DIR
    Out[2]: '/home/yourname/Projects/simple_emp_hr/simple_emp_hr/..'
    

    这相当于/home/yourname/Projects/simple_emp_hr 对吗? 现在我们可以再次使用os.path.join 将目录粘合在一起:

    In [3]: import os
    
    In [4]: os.path.join(settings.PROJECT_DIR, 'foo', 'bar')
    Out[4]: '/home/yourname/Projects/simple_emp_hr/simple_emp_hr/../foo/bar'
    

    我们进入实际设置:

    STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') # you will have something different, I guess
    STATICFILES_DIRS = (
        os.path.join(PROJECT_DIR, 'hr_base', 'static'),
    )
    

    MEDIA_ROOT 的相同练习。

    编辑:我的网址 sn-p 用于静态。一天之内,我无耻地从某个博客上拿了它。

    from django.conf import settings
    from django.conf.urls import patterns, include, url
    from django.contrib import admin
    admin.autodiscover()
    
    urlpatterns = patterns('',
        # normal patterns
    )
    
    if settings.DEBUG:
        urlpatterns += patterns('',
            url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
                {'document_root': settings.STATIC_ROOT, 'show_indexes': True}),
            url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
                {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
        )
    

    【讨论】:

    • 在我的控制台上检查:[18/Feb/2014 12:01:04] "GET /hr_base/css/base.css HTTP/1.1" 404 3640。没有意义
    • 它应该以静态开头。哪个目录通过哪个 url 访问它是如此令人困惑。你能检查一下我之前发布的 url 文件并告诉我是否可以吗?
    • 这变得更糟了,我将 html 转储到控制台进行调试。 {{ STATIC_URL }} 被渲染为空。它实际上什么都没有。
    • 我需要为“STATIC_URL”添加上下文字典条目:settings.STATIC_URL。我使用了命令 python manage.py collectstatic。然后复制了正确的 /static/hr_base/css/base.css 。 html 中的 url 现在看起来没问题。但是,我的浏览器中仍然没有呈现 css。
    • css 文件中的 url 呢?我应该使用 {{STATIC_URL}}/images/bla_bla_bla.jpg 吗?
    【解决方案2】:

    您应该考虑使用 Django 压缩器,http://django-compressor.readthedocs.org/en/latest/ . 它完全值得学习曲线。解决很多问题

    【讨论】:

    • 不。在寻找替代方案之前,OP 需要学习如何使用基础知识。无论如何,这不是答案,应该是评论
    猜你喜欢
    • 2013-08-29
    • 2015-09-22
    • 2012-12-03
    • 2011-12-04
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    相关资源
    最近更新 更多