星期二, 10月 20, 2015

Django 設定建議

Django 設定好文章
reference:
http://www.revsys.com/blog/2014/nov/21/recommended-django-project-layout/
https://docs.djangoproject.com/en/1.8/intro/reusable-apps/


在Django中,樣板templates目錄及statics目錄可以有很多種設定方法:
Project based: 在setting.py中,設定

#設定靜態檔案的系統根目錄
STATIC_ROOT = os.path.join(BASE_DIR, '/static_root') 
STATIC_URL = '/static/'

*其中STATIC_URL是當Server看到/static/目錄的request, 則Server會到STATIC_ROOT下映射去找資料,如果找不到,則會到每個 App目錄下去找static子目錄查詢內容。
*在template中的用法 (helpers function)
static: To link to static files that are saved in STATIC_ROOT Django ships with a static template tag.
{% load static % }
src="{% static "images/hi.jpg" %}"

#設定樣版檔案的系統目錄
TEMPLATE_DIRS = (
    join(BASE_DIR,  'templates'),
)
Deprecated since version 1.8: Set the DIRS option of a DjangoTemplates backend instead. 1.8版要改設一定為DIRS 
TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [
        join(BASE_DIR,  'templates'),
    ],....}

*當Python看到/template/目錄的request, 則Server會到TEMPLATE_DIRS 下映射去找資料,如果找不到,則會到每個 App目錄下去找/templates/子目錄查詢內容。
*在每個app的/template/目前下,建議再建立app名字同名子目錄,方便render函式辨視及搜尋不同app的樣版檔案。例如render(polls/index.html),則系統會依路徑去找,所以會依下列方式 去找
mysite/templates/polls/index.html ,如果找不到,就會找
mysite/polls/templates/polls/index.html


#設定上傳檔案的系統根目錄

MEDIA_ROOT = os.path.join(BASE_DIR, '/upload_root') 
MEDIA_URL = '/upload/'

*在FileField的upload_to會把檔案存在MEDIA_ROOT指定的路徑中。
*在template中的用法 (helpers function)
get_media_prefix: Similar to the get_static_prefix, get_media_prefix populates a template variable with the media prefix MEDIA_URL, e.g.:

{% load static %}
data-media-url="{% get_media_prefix %}">

#設定每個APP urls 路由方式
polls/
    __init__.py
    admin.py
    models.py
    tests.py
    urls.py
    views.py
mysite/urls.py
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', include(admin.site.urls)),
]

其中^polls/結尾不能有$字號, Django 會移除己配對的字串,再把後續字串送到app目錄下的urls模組處理。
polls/urls.py
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]