---
title: "Django使用静态文件"
author: "booby325"
date: "2013-01-28T09:35:18Z"
tags: []
categories: ["Web前端"]
slug: "django"
draft: false
lastmod: "2013-01-28T09:35:18Z"
id: 1776574
url: "https://booby325.iteye.com/blog/1776574"
---

在django1.3中，提供了django.contrib.staticfiles这个模块，方便使用静态文件,显示图片，使用css，js等。  
在设置时需要注意的是：  
1.MEDIA\_ROOT  MEDIA\_URL  
2.STATIC\_ROOT STATIC\_URL  
3.ADMIN\_MEDIA\_ROOT  
4.STATICFILES\_DIRS

In settings.py:  
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('\\\\','/')  
)

In urls.py add these codes:  
from django.conf import settings  
from djagno.conf.urls.static import static  
urlpatterns += static(settings.MEDIA\_URL , document\_root = settings.MEDIA\_ROOT )  
urlpatterns += static(settings.STATIC\_URL, document\_root = settings.STATIC\_ROOT )

in templates:  
{% load static %}  
&lt;img src="{{ get\_static\_prefix }}images/1.jpg" /&gt;  
&lt;link href="{get\_static\_prefix}}css/truple.css /&gt;

很重要的几段话：  
1.# Don't put anything in this directory（STATIC\_ROOT） yourself; store your static files  in apps' "static/" subdirectories and in STATICFILES\_DIRS.

2.The most likely example is user-uploaded content in MEDIA\_ROOT. staticfiles is intended for static assets and has no built-in handling for user-uploaded files, but you can have Django serve your MEDIA\_ROOT by appending something like this to your URLconf:  
     urlpatterns += static(settings.MEDIA\_URL , document\_root = settings.MEDIA\_ROOT )