django 静态文件的配置总结

来源:互联网 发布:液晶电视编程器那种好 编辑:程序博客网 时间:2024/05/29 02:58

django框架的使用,想引用静态css文件,怎么都引用不到,从网搜了好多,大多因为版本问题,
和我现在的使用的dango1.1配置不同,根据资料和公司的项目最终解决,于是想整理总结下各版dango静态文件的配置,以备后查;

配置原因:由于django不处理静态文件(css、js、image等),而是交与web服务器处理。
而django的路径处理和其他web框架有些区别,它需要我们手动的配置静态文件的路径,而不能直接引用。

静态文件的配置的分两种
    第一种为django的开发服务器的配置
    第二种是生产服务器的nginx或apache的web服务配置

第一种,django的开发服务器的静态文件配置,根据django版本的不同,有着比较大的区别。
    dango 1.1静态文件配置:
        1、在项目目录中同settings目录建立static文件夹,其中存放 js 、css 、images文件,可再单独创建文件存放。

我的文件路径:

        2、在settings中增加静态文件目录配置:

STATIC_PATH = os.path.join( os.path.dirname(__file__) , 'static' )

        3、在url.py 中增加静态文件的路径 :

# u静态文件urlpatterns += patterns('',     #(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_PATH}),       (r'^images/(?P<path>.*)$' , 'django.views.static.serve',         {'document_root': os.path.join( settings.STATIC_PATH , 'images' ) } ) ,     (r'^css/(?P<path>.*)$' , 'django.views.static.serve',         {'document_root': os.path.join( settings.STATIC_PATH , 'css' ) } ) ,     (r'^js/(?P<path>.*)$' , 'django.views.static.serve',         {'document_root': os.path.join( settings.STATIC_PATH , 'js' ) } ) ,   )

          4、在模板中引用:

<link href="/css/bootstrap.min.css" rel="stylesheet"><script src="/js/ie-emulation-modes-warning.js"></script>

主要是路径的问题,其他路径应该也可应,比如url.py中的直接使用start/来作为url,以下均匹配,以验证:

# 匹配static 文件夹及子文件夹中的文件(r'^static/(?P<path>.*)$''django.views.static.serve',{'document_root': settings.STATIC_PATH}),  # 匹配image中的文件#(r'^images/(.*)$' , 'django.views.static.serve', {'document_root': os.path.join( settings.STATIC_PATH , 'images' ) } ) ,# 配置css文件价中的文件及子文件夹中的文件#(r'^css/(?P<path>.*)$' , 'django.views.static.serve', {'document_root': os.path.join( settings.STATIC_PATH , 'css' ) } ) ,#(r'^js/(?P<path>.*)$' , 'django.views.static.serve', {'document_root': os.path.join( settings.STATIC_PATH , 'js' ) } ) ,

 

    django 1.3 静态文件配置:

      django1.3提供了django.contrib.staticfiles这个模块,方便使用静态文件,显示图片,使用css等。

默认情况下(如果没有修改STATICFILES_FINDERS的话),Django首先会在STATICFILES_DIRS配置的文件夹中寻找静态文件,然后再从每个app的static子目录下查找,并且返回找到的第一个文件。

settings中新增的配置,MEDIA_ROOT、 MEDIA_URL 、STATIC_ROOT  、STATIC_URL

MEDIA:指用户上传的文件,比如在Model里面的FileFIeld,ImageField上传的文件。如果你定义
MEDIA_ROOT=c:\temp\media,那么File=models.FileField(upload_to="abc/"),上传的文件就会被保存到c:\temp\media\abc。MEDIA_ROOT必须是本地路径的绝对路径。

MEDIA_URL是指从浏览器访问时的地址前缀。

STATIC_ROOT用于存放网站自己的js,css,图片

   注意:不要把你项目的静态文件放到这个目录。这个目录只有在运行manage.py collectstatic时才会用到。 Don't put anything in this directory(STATIC_ROOT) yourself; store your static files  in apps' "static/" subdirectories and in STATICFILES_DIRS.

STATIC_URL的含义与MEDIA_URL类似 

参考步骤如下:

          1、settings配置:

HERE=os.path.dirname(os.path.dirname(__file__)MEDIA_ROOT=os.path.join( HERE , 'media').replace('\\','/')MEDIA_URL = '/media/'STATIC_ROOT =os.path.join( HERE , 'static').replace('\\','/')STATIC_URL= '/static/'ADMIN_MEDIA_ROOT = '/static/admin/' STATICFILES_DIRS = (       os.path.join(HERE,'app1/static/').replace('\\','/'),       os.path.join(HERE,'app2/static/').replace('\\','/'))

         2、url的配置:

from django.conf import settingsfrom djagno.conf.urls.static import staticurlpatterns += static(settings.MEDIA_URL , document_root = settings.MEDIA_ROOT )urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT )

        3、模板的引用:

{% load static %}<img src="{{ get_static_prefix }}images/1.jpg" /><link href="{get_static_prefix}}css/truple.css />

具体配置,视情况而定,并不一定如此配置,仅供参考,待验证--todo;

django 1.3 往后的静态配置目录结构及方法变动比较小。

django1.4 静态配置:

url.py 增加:

## django 自动处理静态文件, 在模板框中可直接通过 static/ 引用from django.contrib.staticfiles.urls import staticfiles_urlpatternsurlpatterns += staticfiles_urlpatterns()

setting.py 配置:

BASEPATH = os.path.join( os.path.dirname( os.path.abspath(__file__) ) ,'..')MEDIA_ROOT = ''MEDIA_URL = ''STATIC_ROOT = os.path.join( BASEPATH, 'static')STATIC_URL = '/static/'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.)STATICFILES_FINDERS = (    'django.contrib.staticfiles.finders.FileSystemFinder',    'django.contrib.staticfiles.finders.AppDirectoriesFinder',    #'django.contrib.staticfiles.finders.DefaultStorageFinder',)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',)import osTEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), '..''templates').replace('\\','/'),)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',    'myapp',)# 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 when DEBUG=False.# 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,    'filters': {        'require_debug_false': {            '()''django.utils.log.RequireDebugFalse'        }    },    'handlers': {        'mail_admins': {            'level''ERROR',            'filters': ['require_debug_false'],            'class''django.utils.log.AdminEmailHandler'        }    },    'loggers': {        'django.request': {            'handlers': ['mail_admins'],            'level''ERROR',            'propagate'True,        },    }}

模板文件:

    <link rel="stylesheet" href="static/css/my.css">    <script src="static/js/jquery.js"></script>

待总结--todo

第二种 生成服务器的配置:

nignx的静态文件的配置:

todo

Apache的静态文件的配置:

todo

参考文档:
http://blog.sina.com.cn/s/blog_3fe961ae01016fpk.html
http://ddtcms.com/news/2011/11/21/18/django-1-3-zhong-xian-shi-tu-pian-shi-yong-jing-tai-wen-jian-de-wen-ti-django-static-files/       
http://blog.csdn.net/wenxuansoft/article/details/8580508

0 0