2013-09-09 18:13:57|  

 
       最近用到Django的静态文件,关于static和media,配置了很多次,终于可以用了。
       首先是static,在'site/site/settings.py'文件中做配置,
import os 
HERE = os.path.split(os.path.realpath(__file__))[0].replace('\\','/')  # 项目settings.py文件所在的文件夹(site)的目录
ROOT = HERE.replace('/site','')  #  项目根目录
 
STATIC_ROOT = os.path.join(ROOT,'static')
 
STATIC_URL = '/static/'
 
STATICFILES_DIRS = (
    ("images", os.path.join(STATIC_ROOT,'images')), 
)
完成之后就可以在模板中使用'/site/static/images/'中的文件了。
例如:
<html lang="zh-CN">
<head>
<title>home</title>
</head>
<body>
    <img src="{{STATIC_URL}}/static/images/1.jpg" width="1024" height="768" alt="site-home" />
</body>
</html>
 
接下来是media,在'site/site/settings.py'文件中做配置,
MEDIA_ROOT = os.path.join(ROOT,'media')
MEDIA_URL = '/media/' 
       然后在'site/site/urls.py'文件中做配置,
urlpatterns += patterns('', 
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT }), 
    )
完成后,在模板中就可以使用'/site/media/images/'中的图片了。
<html lang="zh-CN">
<head>
<title>login</title>
</head>
<body>
    <img src="/media/images/2.jpg" width="1024" height="768" alt="login" />
</body>
</html>

相关文章:

  • 2021-12-09
  • 2022-12-23
  • 2021-10-08
  • 2021-09-21
  • 2022-12-23
  • 2022-12-23
  • 2022-01-07
  • 2021-11-25
猜你喜欢
  • 2022-12-23
  • 2021-07-09
  • 2021-12-18
  • 2021-06-14
  • 2022-12-23
相关资源
相似解决方案