2012-03-22 182 views
4

我想用Django开发一个网站,遵循各种指南,文档和谷歌。我有一些平面页面需要访问图像/ css文件。Django静态文件

我的settings.py文件看起来是这样的:

# Django settings for FirstBlog project. 

DEBUG = True 
TEMPLATE_DEBUG = DEBUG 

ADMINS = (
    # ('Your Name', '[email protected]'), 
) 

MANAGERS = ADMINS 

DATABASES = { 
    'default': { 
     'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 
     'NAME': 'db',      # Or path to database file if using sqlite3. 
     'USER': '',      # Not used with sqlite3. 
     'PASSWORD': '',     # Not used with sqlite3. 
     'HOST': '',      # Set to empty string for localhost. Not used with sqlite3. 
     'PORT': '',      # Set to empty string for default. Not used with sqlite3. 
    } 
} 

# Local time zone for this installation. Choices can be found here: 
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name 
# although not all choices may be available on all operating systems. 
# On Unix systems, a value of None will cause Django to use the same 
# timezone as the operating system. 
# If running in a Windows environment this must be set to the same as your 
# system time zone. 
TIME_ZONE = 'America/Chicago' 

# Language code for this installation. All choices can be found here: 
# http://www.i18nguy.com/unicode/language-identifiers.html 
LANGUAGE_CODE = 'en-us' 

SITE_ID = 3 

# If you set this to False, Django will make some optimizations so as not 
# to load the internationalization machinery. 
USE_I18N = True 

# If you set this to False, Django will not format dates, numbers and 
# calendars according to the current locale 
USE_L10N = True 

# Absolute filesystem path to the directory that will hold user-uploaded files. 
# Example: "/home/media/media.lawrence.com/media/" 
MEDIA_ROOT = '' 

# URL that handles the media served from MEDIA_ROOT. Make sure to use a 
# trailing slash. 
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/" 
MEDIA_URL = '' 

# 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 = '/export/mailgrp4_a/sc10jbr/WWWdev/FirstBlog/djangostatic/' 

# 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/' 

# Additional locations of static files 
STATICFILES_DIRS = (
    '/export/mailgrp4_a/sc10jbr/WWWdev/FirstBlog/static/', 
    # 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. 
) 

# 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', 
) 

# Make this unique, and don't share it with anybody. 
SECRET_KEY = 'nc*v+e13e#!b+dq9mh-vwi0smy#r97#by1w7pvc36ez$j%rz1b' 

# 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', 
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', 
) 

ROOT_URLCONF = 'FirstBlog.urls' 

TEMPLATE_DIRS = (
    '/export/mailgrp4_a/sc10jbr/WWWdev/FirstBlog/templates', 
    # 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. 
) 

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

# A sample logging configuration. The only tangible logging 
# performed by this configuration is to send an email to 
# the site admins on every HTTP 500 error. 
# See http://docs.djangoproject.com/en/dev/topics/logging for 
# more details on how to customize your logging configuration. 
LOGGING = { 
    'version': 1, 
    'disable_existing_loggers': False, 
    'handlers': { 
     'mail_admins': { 
      'level': 'ERROR', 
      'class': 'django.utils.log.AdminEmailHandler' 
     } 
    }, 
    'loggers': { 
     'django.request': { 
      'handlers': ['mail_admins'], 
      'level': 'ERROR', 
      'propagate': True, 
     }, 
    } 
} 

我已经把我的图片/ css文件中FirstBlog/static/images/css。我跑命令

python manage.py collectstatic 

它把我所有的文件在FirstBlog/djangostatic

我想从我的简单页面访问图像的index.html使用标签:

src="{{ /static/ }}images/header.png" 

我已经包含在我的urls.py文件中这一行:

url(r'^static/(.*)$', 'django.views.static.serve', {'document_root':settings.STATIC_PATH}), 

这是给我出现以下错误:

Name Error at /static 

name 'settings' is not defined 

Request Method:  GET 
Request URL: http://127.0.0.1:8000/static 
Django Version:  1.3.1 
Exception Type:  NameError 
Exception Value:  

name 'settings' is not defined 

Exception Location:  /home/cserv2_a/soc_ug/sc10jbr/WWWdev/FirstBlog/../FirstBlog/urls.py in <module>, line 19 

对不起,如果这应该是显而易见的,我花了几个小时看着我NTERNET。

在此先感谢

回答

1

请检查设置是否导入模块在urls.py

+0

即时获取错误:'设置'对象没有属性'STATIC_PATH' – 2012-03-22 14:45:07

+0

将其更改为STATIC_ROOT。更多信息在http://stackoverflow.com/questions/6363728/why-cant-i-get-my-static-dir-to-work-with-django-1-3 – 2012-03-22 14:51:08

+0

谢谢,我觉得我即时得到某处。我的图像标记是:logo我仍然收到一个错误:无法解析其余部分:'/ static /'from'/ static /' – 2012-03-22 14:54:39

0

添加到urls.py

from django.conf import settings

+0

谢谢,我感觉像IM现在取得了一些进展。我的图像标记是:logo我仍然收到错误:无法解析余数:'/ static /'from'/ static /' – 2012-03-22 15:18:46

+1

请勿在模板变量中使用斜杠。 '{{static}}'和{{STATIC_URL}}'很好,但不是'{{/ static /}}'。 – cloudrave 2012-12-16 21:45:31

22

Django是一个梦幻般的系统的开始。功能丰富,但仍然简单,优雅&非常有据可查,具有优秀的例子.....除了静态内容的一切。我们在每个新的Django项目中都与此有关。但我们最近解决了这个问题,我们认为这是“推荐”的方式。

要牢记的关键知识点是Django不想直接提供静态内容。它宁愿将它卸载到底层的网络服务器(如Apache)。有很多方法可以迫使Django为您提供服务 - 您甚至可能认为在一个通用平台上完成所有服务是个好主意。但请听我的话 - 稍后你会后悔的,并希望你只是按照Django的建议。

短篇小说:

这些设置进去“settings.py”

设置STATIC_ROOT到完整的文件系统路径,你要保持你的静态内容。我建议您的常规Web应用程序目录以外的地方。请记住,Apache将直接服务于此,并且您不希望在您的脚下解决安全问题。

设置STATIC_ROOT = '在/ usr /本地/静/ MyProject的/' #包括斜线

设置STATIC_URL = '/静态/' #没有理由让这个

太花哨

设置ADMIN_MEDIA_PREFIX = '/静态/管理/' #别忘了这一个

确保默认STATICFILES_FINDERS设置:

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

,并确保该INSTALLED_APPS设置包括 'django.contrib.staticfiles'

,并确保TEMPLATE_CONTEXT_PROCESSORS包括 'django.core.context_processors.static'

- --- NEXT ----

您将需要配置Apache以直接服务器静态内容。从您的虚拟主机节中,添加如下内容:

Alias /static/ /usr/local/static/MyProject/ 

注:当您设置STATIC_ROOT

代替上面所用的相同路径的路径---- NEXT --- -

在每个应用程序文件夹中,您想要添加到您的任何东西STATIC_ROOT收集到一个名为'static /'的子文件夹中。例如,如果您有一个名为'controller'的应用程序,则应该有一个看起来像'controller/static'的路径

然后从Django项目文件夹的顶部运行'collectstatic'管理子命令的.py。我们通常会创建一个脚本正是如此运行:

#!/usr/bin/sh 
# Scrtipt to collect django static files together. 
# 
# --link Create a symbolic link to each file instead of copying. 
# --noinput Do NOT prompt the user for input of any kind. 
# 
python manage.py collectstatic -link --noinput 
exit 0 

就是这样

你并不需要在urls.py任何条目 - Django将永远也看不到这些要求,所以没有点添加路由条目。

下行

的一个大缺点上文所述,它违背了使用Django的TESTSERVER应用程序的方法。我们从未将它用于任何工作,并且由于我们的最终结果将始终发布到Apache,因此我们发现最好只在那里开发。如果你依赖'testserver' - 有办法解决这个限制。但是,你需要通过Django的挖文档有点https://docs.djangoproject.com/en/dev/howto/static-files/

好运

+0

所有真实但完全不相关的OP,他有一个简单的导入错误。 – 2012-03-22 15:39:46

+0

感谢您的帮助,我的settings.py现在已更新。这不是一个合适的网站,它只是为了一块CW而放在一起,因此它将永远不会被除了Django开发服务器之外的其他任何东西访问。文档说:对于本地开发,如果您使用runserver或将staticfiles_urlpatterns添加到您的URLconf中,则完成设置 - 您的静态文件将自动在默认(用于新创建的项目)/ static /的STATIC_URL上提供。不过,我仍然收到相同的错误。谢谢 – 2012-03-22 15:47:41

+0

哇!即使这不是一个简单的问题答案,我学到了很多阅读你的文章!谢谢! – arijeet 2012-08-06 05:41:29