`
sean_gao
  • 浏览: 224408 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Django: Up and Running

阅读更多

算到现在,已经有将近半年没有写过技术文章了,手痒痒,于是拿Django来说事,希望最终的产出能够做成一个简短易懂的Django快速起步,让初次接触Django的朋友能够在最短的时间内了解Django的基本概念和结构。

Django是使用Python实现的一个基于MVC的web应用框架,类似Ruby世界的Ruby on Rails。如果你是通过Google搜到这篇文章,那么说明你已经对Django有所耳闻,并且愿意了解更多Django相关的信息。我在这里就不多废 话Ruby vs Python或者Rails vs Django,直奔主题。

在写这篇文章时,最新的CPython版本为2.5.1,Django版本为0.96,如无特别说明,本文所有介绍和示例均以此环境为准。

0- 在开始之前,首先当然是安装一个基本能用的开发环境。

如果你的操作系统是Linux或者其他类Unix系统,很可能已经预装了Python,可以在命令行执行python -V查看Python版本。如果你是Windows操作系统,或者想尝试不同版本的Python,那么可以到http://www.python.org/下载相应的安装包进行安装。

有了Python以后,到http://www.djangoproject.com/下载Django,解压以后,cd到解压出来的目录,执行python setup.py install。

为了能够做出一个基本的多层web应用,还需要安装一个数据库,如果没有特别喜好和偏向,推荐PostgreSQL,可以在http://www.postgresql.org/找到合适的版本下载和安装。

我们还缺少一个数据库驱动,在http://www.initd.org/pub/software/psycopg/可以找到用于连接PostgreSQL的psycopg2,安装方法类似Django。

1- django-admin.py startproject

所有环境OK以后,我们开始动手把玩Django,首先找一个干净的目录,执行
$ python django-admin.py startproject hello

上面这行命令会新建一个hello子目录,包含以下文件:
__init.py__: 表示该目录存放Python程序
manage.py: 提供Django项目相关的管理操作
settings.py: 相当于该Django项目的全局设置
urls.py: 用于配置URL映射,基本上就是通过正则表达式指定不同URL由相应的view方法相应

2- manage.py runserver

至此我们已经搭起了一个基本的Django项目框架,执行
$ python manage.py runserver
命令行会提示在8000端口运行一个开发用的web server,转到浏览器的http://localhost:8000/即可看到It worked!的提示信息。你也可以指定端口号,方法是python manage.py runserver XXXX。

3- settings.py

接下来我们做一个完整的从model/数据库到view/template的例子。修改settings.py:
python 代码
  1. ...
  2. DATABASE_ENGINE = 'postgresql_psycopg2'
  3. DATABASE_NAME = 'hello' # Your db name
  4. DATABASE_USER = 'postgres' # Your db user
  5. DATABASE_PASSWORD = '********' # Your db password
  6. DATABASE_HOST = ''
  7. DATABASE_PORT = ''
  8. ...
  9. INSTALLED_APPS = (
  10.     'django.contrib.auth',
  11.     'django.contrib.contenttypes',
  12.     'django.contrib.sessions',
  13.     'django.contrib.sites',
  14.     'hello', # Our new project
  15. )

4- models.py

新建models.py:
python 代码
  1. from datetime import datetime
  2. from django.db import models
  3. class Book(models.Model):
  4.     isbn = models.SlugField(maxlength=20)
  5.     title = models.CharField(maxlength=200)
  6.     author = models.CharField(maxlength=200)
  7.     description = models.TextField(blank=True,null=True)
  8.     published = models.DateTimeField(default=datetime.now)
这 里我们从django.db.models.Model继承我们的model类Book,同时还用到了models中现成的字段类,如 SlugField、CharField、TextField、DateTimeField等。大家比较陌生的恐怕是SlugField,这个基本上类似 CharField,不过增加了其内容需要符合URL要求的限制条件。

执行下面的命令测试数据库脚本的生成:
$ python manage.py sql hello
应该看到如下输出结果:
BEGIN;
CREATE TABLE "hello_book" (
"id" serial NOT NULL PRIMARY KEY,
"isbn" varchar(20) NOT NULL,
"title" varchar(200) NOT NULL,
"author" varchar(200) NOT NULL,
"description" text NULL,
"published" timestamp with time zone NOT NULL
);
COMMIT;

确认无误后可以通过下面的命令提交到数据库:
$ python manage.py syncdb
其间会要求我们创建一个管理员账号,如果暂时不打算做admin页面,可以跳过。

5- views.py

model有了之后,接下来我们就可以开始画视图了。由于篇幅和时间有限,我仅简单介绍一下Django的template,然后实现一个最基本的图书清单页面。

首先定义图书清单的URL,在urls.py中:
python 代码
  1. from django.conf.urls.defaults import *
  2. urlpatterns = patterns('hello.views',
  3.     (r'^hello/books/$', 'book_list'),
  4. )
含义为hello/books/这个URI资源对应的相应view方法为hello.views.book_list。

新建templates目录,然后新建books.html:
xml 代码
 
  1. <html  xmlns="http://www.w3.org/1999/xhtml" lang="zh-cn" xml:lang="zh-cn">  
  2. <head>  
  3. <title>{{ title|escape }}</title>  
  4. </head>  
  5. <body>  
  6. <h2>{{ title }}</h2>  
  7. <table border="1">  
  8.   <tr><th>ISBN</th><th>书名</th><th>作者</th><th>出版日期</th></tr>  
  9.   {% for book in books %}  
  10.   <tr>  
  11.     <td>{{ book.isbn }}</td>  
  12.     <td>{{ book.title }}</td>  
  13.     <td>{{ book.author }}</td>  
  14.     <td>{{ book.published }}</td>  
  15.   </tr>  
  16.   {% endfor %}  
  17. </table>  
  18. </body>  
  19. </html>  
Django模板的语法是{{}}表示引用,{%%}表示代码,使用起来也很直观,甚至支持UNIX风格的filter,如这里的{{ title|escape }}。

新建views.py:
python 代码
  1. from hello.models import *
  2. from django.shortcuts import render_to_response
  3. def book_list(request):
  4.     title = 'Book List'
  5.     books = Book.objects.all()
  6.     return render_to_response('books.html', {'title' : title, 'books' : books})
最终页面上的内容,通过title和books两个参数传递给tempate(books.html)处理。

修改settings.py:
python 代码
  1. TEMPLATE_DIRS = (
  2.     '/opt/Django/hello/templates',
  3. )
指定templates目录位置,注意需要使用绝对路径和'/',无论是Unix还是Windows系统。

我们手工造一些数据之后,就可以通过http://localhost:8000/hello/books/访问我们用Django实现的这个简单页面了。

6- What's next

通过上面的简单介绍,相信哪怕是初次接触Django的朋友,也能够对Django有一个初步的认识。其实Django并不难学,并且随着学习的深入,你一定能发现更多的惊喜,不论是来自Django本身,还是Python及其庞大的第三方类库。

如果有时间,建议尝试一下Django的admin pages,即为我们的model提供自动化、网页化的增删改查操作。启用方法如下:

修改models.py (增加class Admin):
python 代码
  1. class Book(models.Model):
  2.     isbn = models.SlugField(maxlength=20)
  3.     title = models.CharField(maxlength=200)
  4.     author = models.CharField(maxlength=200)
  5.     description = models.TextField(blank=True,null=True)
  6.     published = models.DateTimeField(default=datetime.now)
  7.     class Admin:
  8.         pass

修改settings.py和urls.py,加入admin支持:
python 代码
  1. INSTALLED_APPS = (
  2.      'django.contrib.auth',
  3.      'django.contrib.contenttypes',
  4.      'django.contrib.sessions',
  5.      'django.contrib.sites',
  6.      'django.contrib.admin',
  7.      'hello',
  8. )
python 代码
  1. urlpatterns = patterns('hello.views',
  2.      (r'^hello/books/$', 'book_list'),
  3.      (r'^hello/admin/', include('django.contrib.admin.urls')),
  4. )
Note:
# 为了成功运行admin pages,需要首先执行python manage.py syncdb admin以创建django_admin_log表。
# 如果前面跳过了创建管理员步骤,简单的方法可以删掉auth_user表,然后python manage.py syncdb重建。

按照我们urls.py的配置,admin pages可以通过http://localhost:8000/hello/admin/访问。Enjoy!

分享到:
评论

相关推荐

    learning-django.7z.002

    Learn what you need to know to get up and running with Django with these tutorials from instructor Caleb Smith. Caleb walks through creating a brand-new Django project, defining a data model and ...

    Beginning Django E-Commerce

    "Beginning Django E-... Become versed in the Django web framework and learn how you can put it to use to drastically reduce the amount of work you need to do to get a site up and running quickly.

    Django 1.1 Testing and Debugging.pdf

    Chapter 5: Filling in the Blanks: Integrating Django and Other Test Tools 135 Problems of integration 136 Specifying an alternative test runner 138 Creating a new management command 141 How much ...

    learning-django.7z.001

    Learn what you need to know to get up and running with Django with these tutorials from instructor Caleb Smith. Caleb walks through creating a brand-new Django project, defining a data model and ...

    learning-django.7z.003

    Learn what you need to know to get up and running with Django with these tutorials from instructor Caleb Smith. Caleb walks through creating a brand-new Django project, defining a data model and ...

    learning-django.7z.004

    Learn what you need to know to get up and running with Django with these tutorials from instructor Caleb Smith. Caleb walks through creating a brand-new Django project, defining a data model and ...

    django-scholarec:基于Django的推荐引擎,它使用Scholarec(https

    为了继续,您需要具备: Django&gt;=1.5 installed.(Refer: https://www.djangoproject.com/download/ )ElasticSearch(0.90.11) instance up and running. (Refer: http://elasticsearch.org )首次使用时,请在L​​...

    High Performance Django 2015.3

    There are tutorials and books that literally walk you through the process of getting your first site up and running. Taking that code from your laptop to the real world is like opening pandora’s box...

    Packt.Python.Journey.from.Novice.to.Expert.2016

    Get Python up and running on Windows, Mac, and Linux in no time Grasp the fundamental concepts of coding, along with the basics of data structures and control flow Understand when to use the ...

    Apress.Beginning.CouchDB.Dec.2009.pdf

    CouchDB up and running on your computer that’s running Linux or Mac OS X. It guides you through the process of creating a database and working with data; covers more complex topics such as views and ...

Global site tag (gtag.js) - Google Analytics