Django中配置靜態文件路徑

選擇了最近一直在看的Django作爲我的Android Demo的server端,今天想要實現一個Android下上傳文件到服務器的功能,於是想了想,暫時可以先放到靜態文件目錄下,然後就把自己配置靜態文件目錄的過程記錄一下。

首先打開你的項目下的settings.py文件,在其中加入或修改如下代碼:

# 設置一個路徑變量
APP_PATH=os.path.dirname(os.path.dirname(__file__))
# 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.
# 注意要修改STATIC_ROOT變量
STATIC_ROOT = os.path.join(APP_PATH,'static').replace('\\','/')

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'

# 當然還有STATICFILES_DIRS變量
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.
    os.path.join(APP_PATH,'mobile_oa_server/static').replace('\\','/'),
)
然後在你的項目下的urls.py文件中加入如下代碼:

# 導入static和settings
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = patterns('',
	# 這裏是你原先的urlpatterns的值,記住一定要在urlpatterns的下方,追加static
)
urlpatterns+=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)

OK,完成了上述步驟之後,我們可以在我們的app目錄下創建一個static文件夾,然後扔一張照片啥的進去,爲了檢測是否成功:效果如下(隨便找了張圖作測試)


夜已深,收拾完這個小東西就準備睡覺去了,明天又是要奮鬥的一天,大家加油!

2013年11月17日,Eric.Tang 記


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章