版本:1.0

版本说明:

1) 大部分来源于http://www.cnblogs.com/cacique/archive/2012/09/29/2707976.html

2) 自己测试用,使用svn比较方便


 

以下详细步骤

1. create folder
mysite2

2. cmd to  mysite2
django-admin.py startproject blog

#F:\tools\Django-1.5\build\scripts-2.7\django-admin.py 是Django 安装路径
此时目录结构如下
blog/
    manage.py
    blog/
        __init__.py
        settings.py
        urls.py
        wsgi.py
        
打开IE check
http://localhost:8000/admin/
show "It worked!"

3. create blogapp
manage.py startapp sblog

blog/
sblog/
    __init__.py
    models.py
    tests.py
    views.py
manage.py

4. change database
全局修改,当然在settings.py中
.\mysite2\blog\blog\settings.py
1) 新建一下数据库文件
.\mysite2\blog\db\mydata.db
2) 配置

 1 DATABASES = {
 2     'default': {
 3         'ENGINE': r'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
 4         'NAME': BASE_DIR+r'/../db/mydata.db',                      # Or path to database file if using sqlite3.
 5         # The following settings are not used with sqlite3:
 6         'USER': '',
 7         'PASSWORD': '',
 8         'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
 9         'PORT': '',                      # Set to empty string for default.
10     }
11 }

相对路径方法,在settings.py中
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
'NAME': BASE_DIR+r'\..\db\django.db',

5. 增加模块

modify .\mysite2\blog\sblog\models.py

 1 from django.db import models
 2 
 3 
 4 class Tag(models.Model):
 5     """docstring for Tags"""
 6     tag_name = models.CharField(max_length=20, blank=True)
 7     create_time = models.DateTimeField(auto_now_add=True)
 8 
 9     def __unicode__(self):
10         return self.tag_name
11 
12 
13 class Author(models.Model):
14     """docstring for Author"""
15     name = models.CharField(max_length=30)
16     email = models.EmailField(blank=True)
17     website = models.URLField(blank=True)
18 
19     def __unicode__(self):
20         return u'%s' % (self.name)
21 
22 
23 class Blog(models.Model):
24     """docstring for Blogs"""
25     caption = models.CharField(max_length=50)
26     author = models.ForeignKey(Author)
27     tags = models.ManyToManyField(Tag, blank=True)
28     content = models.TextField()
29     publish_time = models.DateTimeField(auto_now_add=True)
30     update_time = models.DateTimeField(auto_now=True)
31 
32     def __unicode__(self):
33         return u'%s %s %s' % (self.caption, self.author, self.publish_time)

       
6. 修改URL访问
.\mysite2\blog\blog\setting.py

 1 MIDDLEWARE_CLASSES = (
 2     'django.middleware.common.CommonMiddleware',
 3     'django.contrib.sessions.middleware.SessionMiddleware',
 4     'django.middleware.csrf.CsrfViewMiddleware',
 5     'django.contrib.auth.middleware.AuthenticationMiddleware',
 6     'django.contrib.messages.middleware.MessageMiddleware',
 7     'django.middleware.locale.LocaleMiddleware', # add
 8     # Uncomment the next line for simple clickjacking protection:
 9     # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
10 )
11 INSTALLED_APPS = (
12     'django.contrib.auth',
13     'django.contrib.contenttypes',
14     'django.contrib.sessions',
15     'django.contrib.sites',
16     'django.contrib.messages',
17     'django.contrib.staticfiles',
18     # Uncomment the next line to enable the admin:'django.contrib.admin',
19     # Uncomment the next line to enable admin documentation:
20     'django.contrib.admindocs',   # add
21     'sblog',   # add
22 )

7. validate
python manage.py validate

8. 创建数据库
manage.py syncdb

因为我们修改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管理 ,创建用户就可以了

9. admin的配置使用
修改blog 目录下 urls.py
添加
from django.contrib import admin
admin.autodiscover()
在 patterns 添加 (如果一直没改过该文件的话 只要将这两行注释去掉就可以了)

1 url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
2 url(r'^admin/', include(admin.site.urls)),

10. 把sblog加入管理,这步实现原理是啥?
首先在sblog目录下新建admin.py 添加以下内容 再刷新admin页面

 1 #!/usr/bin/python
 2 # -*- coding: utf-8 -*-
 3 
 4 from django.contrib import admin
 5 from sblog.models import Author, Blog, Tag
 6 
 7 
 8 class AuthorAdmin(admin.ModelAdmin):
 9     """docstring for AuthorAdmin"""
10     list_display = ('name', 'email', 'website')
11     search_fields = ('name',)
12 
13 
14 class BlogAdmin(admin.ModelAdmin):
15     """docstring for BlogAdmin"""
16     list_display = ('caption', 'id', 'author', 'publish_time')
17     list_filter = ('publish_time',)
18     date_hierarchy = 'publish_time'
19     ordering = ('-publish_time',)
20     filter_horizontal = ('tags',)
21     # raw_id_fields = ('author',)  # 它是一个包含外键字段名称的元组,它包含的字段将被展现成`` 文本框`` ,而不再是`` 下拉框`` 。
22 
23 
24 admin.site.register(Author, AuthorAdmin)
25 admin.site.register(Blog, BlogAdmin)
26 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框,还可以移回来

11. 在视图中使用模板
方法1

1 from django.template import Template, Context
2 from django.http import HttpResponse
3 import datetime
4 
5 def current_datetime(request):
6     now = datetime.datetime.now()
7     t = Template("<html><body>It is now {{ current_date }}.</body></html>")
8     html = t.render(Context({'current_date': now}))
9     return HttpResponse(html)

它使用了模板系统,但是模板仍然嵌入在Python代码里,并未真正的实现数据与表现的分离。 现在让我们将模板置于一个单独的文件 中,并且让视图加载该文件来解决此问题。
方法2

首先在项目目录下新建templates文件夹 然后在templates下新建sblog文件夹和base.html文件

目录结构为

templates/
  -sblog/
  -base.html

然后修改setting.py, BASE_DIR 见上面

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

12. 编写base.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>
        {% block title %}{% endblock %}        
    </title>
</head>

<body>
    <h1>a simple blog</h1>
    {% block content %}
    {% endblock %}
    {% block footer %}
    {# 任何每个页面都可能修改的文本区域的页脚 #} # 这句导致网页无法访问,后删除之
        <p>Thanks for visiting my site! </p>
    {% endblock %}
</body>
</html>
这个叫做 base.html 的模板定义了一个简单的 HTML 框架文档,我们将在本站点的所有页面中使用。 所有的子模板都在重载、添加或保留base.html块的内容。
{% block %}: 所有的 {% block %} 标签告诉模板引擎,子模板可以重载这些部分。 每个{% block %}标签所要做的是告诉模板引擎,该模板下的这一块内容将有可能被子模板覆盖。

然后在sblog目录下新建blog_list.html 添加以下内容

 1 {% extends "base.html" %}
 2 
 3 {% block title %} blog list {% endblock %}
 4 
 5 
 6 {% block content %}
 7 <div class="content">
 8     {% for blog in blogs %}
 9         <h3>{{ blog.caption }}</h3>
10         <div>{{ blog.content}} </div>
11     {% endfor %}     
12 </div>    
13 {% endblock %}

13. 在sblog目录下views.py文件添加 内容

1 from django.shortcuts import render_to_response
2 from sblog.models import Blog
3 
4 
5 def blog_list(request):
6     blogs = Blog.objects.all()
7     return render_to_response("blog_list.html", {"blogs": blogs})

14. 添加url
现在视图和模板都完成了,让我们添加url吧

首先修改blog目录下urls.py 文件 添加

1 urlpatterns += patterns((''),
2     (r'^sblog/', include('sblog.urls')),
3 )

然后修改sblog目录下添加urls.py文件,内容如下:

 1 #!/usr/bin/python
 2 # -*- coding: utf-8 -*-
 3 
 4 from django.conf.urls import *
 5 
 6 
 7 urlpatterns = patterns(('sblog.views'),
 8     url(r'^bloglist/$', 'blog_list', name='bloglist'),
 9     # name属性是给这个url起个别名,可以在模版中引用而不用担心urls文件中url的修改 引用方式为{% url bloglist %}
10 )

15. 错误处理

Unicode error hint

The string that could not be encoded/decoded was: {# ??????
Error during template rendering

In template F:\work\svn\mysite2\blog\templates\sblog\blog_list.html, error at line 1

因为base.html中有中文。

16. 测试

浏览器输入

http://localhost:8000/admin/

http://localhost:8000/sblog/bloglist/

17. 修改blog list排序
只要在需要现实的模块中加入class Meta

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)
        
    # TIPS configure order
    class Meta:
        ordering = ['-publish_time']
        
18. 美化博客显示
添加 .\mysite2\blog\templates\sblog\blog_show.html

与页面匹配的需要视图
views.py 添加blog_show 视图

1 from django.http import Http404
2 
3 def blog_show(request, id=''):
4     try:
5         blog = Blog.objects.get(id=id)
6     except Blog.DoesNotExist:
7         raise Http404
8     return render_to_response("blog_show.html", {"blog": blog})

   
修改sblog下urls.py (如果不特殊说明,以后修改urls.py文件默认就是sblog目录下的)添加以下内容
url(r'^blog/(?P<id>\d+)/$', 'blog_show', name='detailblog'),

修改blog_list.html
<h3>{{ blog.caption }}</h3>
改为
<h3><a href="{% url detailblog blog.id %}">{{ blog.caption }}</a></h3>
{% url detailblog blog.id %} 中 blog.id 是
url(r'^blog/(?P<id>\d+)/$', 'blog_show', name='detailblog'),的 (?P<id>\d+) 参数

19. 错误处理二
'url' requires a non-empty first argument. The syntax changed in Django 1.5, see the docs.

Request Method:     GET
Request URL:     http://localhost:8000/sblog/bloglist/
Django Version:     1.5
Exception Type:     NoReverseMatch
Exception Value:     

'url' requires a non-empty first argument. The syntax changed in Django 1.5, see the docs.

Exception Location:     C:\Python27\lib\site-packages\django\template\defaulttags.py in render, line 402
Python Executable:     C:\Python27\python.exe
Python Version:     2.7.3

把<h3><a href="{% url detailblog blog.id %}">{{ blog.caption }}</a></h3>修改为
<h3><a href="{% url 'detailblog' blog.id %}">{{ blog.caption }}</a></h3>

参考
About url-template-tags

url-template-tags change in django1.5 from

    {% url something.else foo bar %}

to

    {% url "something.else" foo bar %}

fix all like this (backup all file before use this):

find . -type f -print0 | xargs -0 sed -i 's/ url \([^" >][^ >]*\)/ url "\1"/g'