【Django实例】博客1

(上一篇)

一、概述

Blog是一个博客应用。

dbe工程的目录结构,参考《序言》的最后部分。blog应用位于/home/russellluo/Django/dbe/dbe/blog目录下,blog目录的内容如下:

blog/
    admin.py     (后台管理)
forms.py     (表单)
__init__.py (空文件,让Python能够将blog目录识别为一个package)
models.py    (数据库层)
tests.py     (测试)
urls.py      (URL映射)
views.py     (视图)

二、功能体验

因为blog应用是DBE中的第一个实例,所以对于如何配置和使用Django工程的研究会稍微细致一点。后面的实例中会跳过这些相同的细节,有疑问可以参考本篇内容,或者直接翻阅官方经典《The Django Book》 :-)

1. 配置blog

1)添加blog应用

这里不必使用"python manage.py startapp blog"新建blog应用,因为完整的blog源码已经就位。

打开/home/russellluo/Django/dbe/dbe/settings.py,找到INSTALLED_APPS,将blog应用添加到末尾:

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',
    'dbe.blog',  # 添加的blog应用
)

因为dbe工程主目录/home/russellluo/Django/dbe会被添加到Python搜索路径中(参考《Chapter 3: Views and URLconfs》侧边栏"Your Python Path"),因此"dbe.blog"就代表/home/russellluo/Django/dbe/dbe/blog目录对应的package。

2)配置数据库

blog/models.py中用到了Django的数据库层,因此需要为新建的dbe工程配置数据库。

打开/home/russellluo/Django/dbe/dbe/settings.py,找到DATABASES

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '',                      # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': '',
        'PASSWORD': '',
        'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '',                      # Set to empty string for default.
    }
}

因为Django自带sqlite3引擎,简便起见,这里使用sqlite3数据库,由此只需要配置'ENGINE'和'NAME'即可:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '/home/russellluo/Django/dbe/dbe/sqlite3.db',                      # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': '',
        'PASSWORD': '',
        'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '',                      # Set to empty string for default.
    }
}

3)配置URL映射

blog/urls.py中明确给出了blog应用的URL映射关系,将这些配置信息拷贝到dbe工程的URL映射文件/home/russellluo/Django/dbe/dbe/urls.py中:

# -*- coding: utf-8 -*-

from
django.conf.urls import patterns, include, url # 1.以下三行import语句拷贝自blog/urls.py from django.conf.urls.defaults import * from dbe.blog.models import * from dbe.blog.views import PostView, Main, ArchiveMonth # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'dbe.views.home', name='home'), # url(r'^dbe/', include('dbe.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)), ) # 2.以下部分拷贝自blog/urls.py(为了不覆盖前面的URL映射,将原来的"="改成了更友好的"+=") urlpatterns += patterns("dbe.blog.views", (r"^post/(?P<dpk>d+)/$" , PostView.as_view(), {}, "post"), (r"^archive_month/(d+)/(d+)/$" , ArchiveMonth.as_view(), {}, "archive_month"), (r"^$" , Main.as_view(), {}, "main"), # (r"^delete_comment/(d+)/$" , "delete_comment", {}, "delete_comment"), )

4)配置Template路径

blog/views.py中使用了模板文件:如blog/list.html和blog/post.html,它们都位于/home/russellluo/Django/dbe/dbe/templates目录下,为了让Django能够成功找到这些template模板,需要配置Template路径。

打开/home/russellluo/Django/dbe/dbe/settings.py,修改TEMPLATE_DIRS如下

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.
    '/home/russellluo/Django/dbe/dbe/templates'
, )

2. 运行blog

1)一片空白的博客

完成上述配置后,blog应用就成功地添加到了dbe工程中。

为了观察blog应用的实际效果,需要执行以下三个步骤:

a)创建数据库的表:

$ cd /home/russellluo/Django/dbe
$ python manage.py syncdb Creating tables ... Creating table auth_permission Creating table auth_group_permissions Creating table auth_group Creating table auth_user_groups Creating table auth_user_user_permissions Creating table auth_user Creating table django_content_type Creating table django_session Creating table django_site Creating table blog_post Creating table blog_comment

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): yes
Username (leave blank to use 'rusellluo'): rusellluo
Email address: me@cnblogs.com
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

      每一行Creating table **的打印表示对应创建了一个**表。以auth_和django_开头的表都用于Django的自带应用(这些应用都是默认注册好的,当然也可以通过修改settings.py去掉它们)。

      以blog_开头的才是blog应用使用的表:blog_post和blog_comment(二者分别对应于Post和Comment两个Model类)。

      特别地,如果是第一次创建数据库的表,Django的auth system(认证系统)会提醒你输入用于登录“后台管理”平台的账户和邮箱信息等,按照提示输入即可。

      创建完数据库的表以后,用ls命令查看/home/russellluo/Django/dbe/dbe目录,会发现多了一个数据库文件sqlite3.db。

      关于数据库层(Django的Model类)的基础知识,请参考《Chapter 5: Models》

b)开启Django自带的服务器:

$ python manage.py runserver
Validating models...

0 errors found
June 16, 2013 - 05:38:25
Django version 1.5.1, using settings 'dbe.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

      开启服务器前,manage.py脚本会首先自动检测数据库表的有效性(Validating models...),如果发现没有错误(0 errors found),才会成功开启服务器,否则将显示出错信息并终止退出。

      对数据库表的检测也可以在开启服务器前手动触发:

$ python manage.py validate
0 errors found

c)进入127.0.0.1:8000主页:

      在浏览器地址栏中输入127.0.0.1:8000并回车后,可以看到以下页面:

      显而易见,载入页面时遇到了错误,错误位于"In template /home/russellluo/Django/dbe/dbe/templates/blog/list.html, error at line 1",提示原因"/home/russellluo/Django/dbe/dbe/templates/bbase.html (File does not exist)"。由此可知,该错误是由于 {% extends "bbase.html" %} 一行中,Django在TEMPLATE_DIRS所指定的路径下查找bbase.html失败,因为blog应用使用的bbase.html位于/home/russellluo/Django/dbe/dbe/templates/blog中。

      消除这个错误的方法有两种:

  • 保留bbase.html的写法,在TEMPLATE_DIRS中新增一个模板搜索路径,使得Django可以成功找到bbase.html
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.
    '/home/russellluo/Django/dbe/dbe/templates'
,
    '/home/russellluo/Django/dbe/dbe/templates/blog', )

      需要注意的是,如果一个Django工程中有多个应用使用了相同名称的模板文件(如blog/bbase.html、forum/bbase.html),那么保留bbase.html的写法会有问题。因为Django查找模板文件时,会顺序搜索TEMPLATE_DIRS中给出的路径,因此任何直接写bbase.html的地方都会最终使用到blog/bbase.html,而不是该应用真正对应的那个bbase.html(如forum应用真正对应forum/bbase.html,但却使用的是blog/bbase.html)。

  • TEMPLATE_DIRS的配置不变,修改bbase.html的写法,改为 {% extends "blog/bbase.html" %}

      幸运的是,在dbe工程中上述两种方法都可行。因为DBE源码中不存在相同名称的模板文件,所以方法一没问题;如果使用方法二,对于blog应用而言,需要修改blog/list.html和blog/post.html两个模板文件中的extends处理。

      消除错误后,重新进入127.0.0.1:8000主页:

      现在一切正常了!但是映入眼帘的blog主页未免也显得太单调了:除了两行英文以外,再没有其他有意义的内容,也没有任何链接可跳到其他页面。

      blog应用的主要功能是发表文章和允许评论,所以起码要有人撰写文章才会有内容呈现。此时就需要使用Django的后台管理系统(Admin Site)。

2)有文章,有评论,这才叫博客

要使用Django的后台管理系统撰写文章,需要两步操作:

  • 开启Admin功能
  • 利用后台管理界面撰写并保存文章(添加Post数据)

由于Admin是Django通用的后台管理系统,与本篇blog应用的具体内容关系不大。详细的使用方法在《Chapter 6: The Django Admin Site》中有很好的讲解,因此这里不再赘述。

使用Django后台撰写好文章后,再次打开blog主页:

 

点击"Admin"链接可以进入后台管理系统的主界面:

点击"Add post"链接可以直接进入撰写文章的界面:

点击"Comments (0)"链接则可以查看并评论该文章:

后面的操作跟平常上网看文章没啥区别了,就不再一一演示,可以自己实际动手体验一下。

原文地址:https://www.cnblogs.com/russellluo/p/3138135.html