django 简易博客开发 1 安装、创建、配置、admin使用

首先贴一下项目地址吧  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管理我们的博客 

                                                                                                                                                               下一篇 将会介绍如何使用模板将我们的博客显示出来

posted @ 2012-09-29 10:59  cacique  阅读(39849)  评论(14编辑  收藏  举报
Copyright ©2011 Goodspeed Cheng