首先貼一下項目地址吧 https://github.com/goodspeedcheng/sblog
到現在位置項目實現的功能有:
1、后台管理使用Admin ,前端顯示使用bootstrap
2、評論使用的系統自帶comments 支持ajax
3、支持markdown 代碼高亮 使用markdown + Pygments
4、使用的gravatar頭像服務
使用的環境: fedora 17 + django1.4 + python2.7 + sqlite3
需要的模塊支持: markdown + Pygments 其它 django第三方app使用時再介紹
現在正式開始博客開發
1、安裝django1.4
如果你使用的是fedoraDVD版,安裝時選擇了web開發組建,這一步可以省略,因為它自帶django環境
django下載地址 https://www.djangoproject.com/download/ 這里我們選擇最新版
然后在終端下打開下載目錄
tar xzvf Django-*.tar.gz 。 cd Django-* 。 sudo python setup.py install
如果系同時window
解壓后再控制台進入解壓后的目錄
python setup.py install
測試安裝
打開Python的交互解釋器
如果出現以下內容,安裝成功!
>>> import django >>> django.VERSION (1, 4, 1, 'final', 0)
2、新建project
打開終端 輸入
django-admin startproject blog
有些需要輸入
django-admin.py startproject blog
你會發現主文件夾下多出一個目錄 blog
目錄結構為
blog/ manage.py blog/ __init__.py settings.py urls.py wsgi.py
manage.py :一種命令行工具,可讓你以多種方式與該 Django 項目進行交互。 鍵入python manage.py help,看一下它能做什么。
__init__.py :讓 Python 把該目錄當成一個開發包 (即一組模塊)所需的文件。 這是一個空文件,一般你不需要修改它
settings.py :該 Django 項目的設置或配置。 查看並理解這個文件中可用的設置類型及其默認值
urls.py:django項目的URL設置。 可視其為你的django網站的目錄
wsgi.py: An entry-point for WSGI-compatible webservers to serve your project.See How to deploy with WSGI for more details.
具體使用方法參考 文檔 https://docs.djangoproject.com/en/1.4/intro/tutorial01/
運行服務器
在終端打開項目目錄 輸入
python manage.py runserver
Validating models... 0 errors found Django version 1.4.1, using settings 'blog.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
出現以上選項說明運行服務器成功
訪問 http://127.0.0.1:8000/ 你將看到
3、新建blogapp
在終端打開項目目錄輸入
python manage.py startapp sblog
現在新建好了一個名為sblog的博客應用
sblog/ __init__.py models.py tests.py views.py
這個目錄包含了這個app的模型和視圖
4、models的配置
因為使用app必須用到數據庫,現在我們配置一下數據庫 打開setting.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '/home/gs/blog/datas/mydata.db', # 這里是我數據庫文件存放的目錄,你應該替換成你自己的. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } }
因為python自帶sqlite3,為了方便我們就直接使用。
其它數據庫的配置參見 https://docs.djangoproject.com/en/1.4/ref/databases/
現在我們配置models.py
from django.db import models class Tag(models.Model): """docstring for Tags""" tag_name = models.CharField(max_length=20, blank=True) create_time = models.DateTimeField(auto_now_add=True) def __unicode__(self): return self.tag_name class Author(models.Model): """docstring for Author""" name = models.CharField(max_length=30) email = models.EmailField(blank=True) website = models.URLField(blank=True) def __unicode__(self): return u'%s' % (self.name) class Blog(models.Model): """docstring for Blogs""" caption = models.CharField(max_length=50) author = models.ForeignKey(Author) tags = models.ManyToManyField(Tag, blank=True) content = models.TextField() publish_time = models.DateTimeField(auto_now_add=True) update_time = models.DateTimeField(auto_now=True) def __unicode__(self): return u'%s %s %s' % (self.caption, self.author, self.publish_time)
安裝 models
首先修改setting.py
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.middleware.locale.LocaleMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) 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', # Uncomment the next line to enable admin documentation: 'django.contrib.admindocs', 'sblog', )
然后,用下面的命令對校驗模型的有效性:
python manage.py validate
validate 命令檢查你的模型的語法和邏輯是否正確。 如果一切正常,你會看到 0 errors found 消息。 如果有問題,它會給出非常有用的錯誤信息來幫助你 修正你的模型。
最后
python manage.py syncdb
你將看到類似與下面的內容
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table django_admin_log
Creating table sblog_tag
Creating table sblog_author
Creating table sblog_blog_tags
Creating table sblog_blog
因為我們修改setting.py時將
'django.contrib.admin', 'django.contrib.admindocs',
注釋去掉了,所以在 執行
python manage.py syncdb
時會 出現You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no):
讓我們新建用戶用於admin管理 ,創建用戶就可以了
5、admin的配置使用
修改blog 目錄下 urls.py
添加
from django.contrib import admin admin.autodiscover()
在 patterns 添加 (如果一直沒改過該文件的話 只要將這兩行注釋去掉就可以了)
url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)),
此時 打開 http://127.0.0.1:8000/admin/
就可以使用admin了,登錄之后界面為
如果你發現我們新建的sblog並沒有出現,恭喜你,你有很強的觀察能力,很細心,很。。。。
我還是接着說怎么用admin管理我們的sblog吧。
首先再sblog目錄下新建admin.py 添加以下內容 再刷新admin頁面 將會有驚喜哦
#!/usr/bin/python # -*- coding: utf-8 -*- from django.contrib import admin from sblog.models import Author, Blog, Tag class AuthorAdmin(admin.ModelAdmin): """docstring for AuthorAdmin""" list_display = ('name', 'email', 'website') search_fields = ('name',) class BlogAdmin(admin.ModelAdmin): """docstring for BlogAdmin""" list_display = ('caption', 'id', 'author', 'publish_time') list_filter = ('publish_time',) date_hierarchy = 'publish_time' ordering = ('-publish_time',) filter_horizontal = ('tags',) # raw_id_fields = ('author',) # 它是一個包含外鍵字段名稱的元組,它包含的字段將被展現成`` 文本框`` ,而不再是`` 下拉框`` 。 admin.site.register(Author, AuthorAdmin) admin.site.register(Blog, BlogAdmin) admin.site.register(Tag)
其中 AuthorAdmin 和 BlogAdmin 是 自定義ModelAdmi類 用於自定義admin顯示
list_display = ('caption', 'id', 'author', 'publish_time') 表示 按照 caption id author publish_time 顯示 另外,點擊每個列的列頭可以對那列進行排序。search_fields = ('name',) 刷新瀏覽器,你會在頁面頂端看到一個查詢欄。我們剛才所作的修改列表頁面,添加了一個根據姓名查詢的查詢框list_filter = ('publish_time',) 用於在右邊生成一個過濾器,按照發表時間過濾date_hierarchy = 'publish_time' 也是時間過濾器 修改好后,頁面中的列表頂端會有一個逐層深入的導航條,它從可用的年份開始,然后逐層細分到月乃至日。ordering = ('-publish_time',) 按照發表時間排序 默認是從前往后排序 加‘-’表示將最近發表的放到前面,從后往前倒序排列filter_horizontal = ('tags',) 用於多對多字段顯示,出現一個精巧的JavaScript過濾器,它允許你檢索選項,然后將選中的tag從Available框移到Chosen框,還可以移回來
其它一些自定義方法參見文檔吧 https://docs.djangoproject.com/en/1.4/ref/contrib/admin/
到現在為止,我們已經可以使用admin管理我們的博客
下一篇 將會介紹如何使用模板將我們的博客顯示出來