高見龍

iOS app/Ruby/Rails Developer & Instructor, 喜愛非主流的新玩具 :)

Django的Flatpage

Django的功能很多,但假設其實你根本不需要這麼多資料庫相關的功能,你只是想做個簡單的個人簡介頁面,然後有個簡單的後台管理介面可以讓你更新內容就好,那你也許可以使用Django的Flatpage就行了。

使用方式很簡單,只要把一些module加上去就行了。請打開settings.py,在INSTALLED_APPS加上django.contrib.flatpages

1
2
3
4
5
6
7
8
9
10
11
12
13
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',
    'django.contrib.flatpages',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

並且在MIDDLEWARE_CLASSES加上django.contrib.flatpages.middleware.FlatpageFallbackMiddleware

1
2
3
4
5
6
7
8
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',
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)

然後,你可能需要改一下TEMPLATE_DIRS,設定一下template的路徑:

1
2
3
4
5
6
7
PROJECT_BASE_DIR = os.path.dirname(__file__).replace('\\', '/')
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    PROJECT_BASE_DIR + '/templates',
)

PS: 感謝 Lazkey 提醒,TEMPLATE_DIRS 裡請使用絕對路徑。

urls.py記得把Admin模組相關的設定打開:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from django.conf.urls.defaults import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^mysite/', include('mysite.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)

再來執行一下syncdb:

> python manage.py syncdb

這樣就設定完成了。進到Admin介面,你應該可以看到多了一個"簡平頁面"的功能(如果你沒改語系的話,應該會看到Flatpage):

image

然後你就可以開始新增頁面了。不過在新增頁面的最下面有個Sites選項要特別注意,預設是www.example.com,這邊要把它換成我們自己的網址。以本機為例,加入了127.0.0.1:8000。又,因為這個site是我們後來新加的,所以要讓它生效的話,需要再回頭來改一下settings.pySITE_ID

1
  SITE_ID = 2

最後,你還需要做個template給它用:

Flatpage HTML (flatpage.html) download
1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html>
<head>
<title>{{ flatpage.title }}</title>
</head>
<body>
{{ flatpage.content }}
</body>
</html>

把上面這些內容存在 templates/flatpages/default.html,重新整理之後,應該就可以看得到內容了。

更多詳細內容及使用方式,請見Django官網 - Flatpage章節

Comments