初学python的Web框架Django

1下载

bear@njava:~$wget http://www.djangoproject.com/download/1.2/tarball/
bear@njava:~$tar -xzvf Django-1.2.tar.gz
bear@njava:~$cd Django-1.2/
bear@njava:~$sudo python setup.py install

2 新建django项目

bear@njava:~$ django-admin.py startproject njava
bear@njava:~$cd njava
bear@njava:~$ls
total 20K
drwxr-xr-x 2 bear bear 4.0K 2010-05-19 23:27 .
drwxr-xr-x 4 bear bear 4.0K 2010-05-19 23:27 ..
-rw-r--r-- 1 bear bear    0 2010-05-19 23:27 __init__.py
-rw-r--r-- 1 bear bear  546 2010-05-19 23:27 manage.py
-rw-r--r-- 1 bear bear 3.3K 2010-05-19 23:27 settings.py
-rw-r--r-- 1 bear bear  534 2010-05-19 23:27 urls.py
bear@njava:~$python manage.py runserver 0.0.0.0:8000

3 设置数据库链接

bear@njava:~$vi settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '',                      # Or path to database file if using sqlite3.
        '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.
    }
}

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
)

bear@njava:~$python manage.py syncdb

1 If you’re new to databases, we recommend simply using SQLite (by setting ENGINE to ‘django.db.backends.sqlite3’). SQLite is included as part of Python 2.5 and later, so you won’t need to install anything else.

2 While you’re editing settings.py, take note of the INSTALLED_APPS setting towards the bottom of the file. That variable holds the names of all Django applications that are activated in this Django instance. Apps can be used in multiple projects, and you can package and distribute them for use by others in their projects.

3 The syncdb command will only create tables for apps in INSTALLED_APPS.

4 模型建立

Projects vs. apps的概念
What’s the difference between a project and an app? An app is a Web application that does something — e.g., a weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects.

建立一个新闻的app

bear@njava:~$python manage.py startapp news
bear@njava:~$ ls -alh
total 72K
drwxr-xr-x 3 bear bear 4.0K 2010-05-19 23:58 .
drwxr-xr-x 4 bear bear 4.0K 2010-05-19 23:27 ..
-rw-r--r-- 1 bear bear    0 2010-05-19 23:27 __init__.py
-rw-r--r-- 1 bear bear  131 2010-05-19 23:37 __init__.pyc
-rw-r--r-- 1 bear bear  546 2010-05-19 23:27 manage.py
drwxr-xr-x 2 bear bear 4.0K 2010-05-19 23:58 news
-rw-r--r-- 1 bear bear 3.3K 2010-05-19 23:48 settings.py
-rw-r--r-- 1 bear bear 2.0K 2010-05-19 23:48 settings.pyc
-rw-r--r-- 1 bear bear  32K 2010-05-19 23:52 tt.db
-rw-r--r-- 1 bear bear  534 2010-05-19 23:27 urls.py
-rw-r--r-- 1 bear bear  231 2010-05-19 23:37 urls.pyc
bear@njava:~$ cd news
bear@njava:~/news$ ls
__init__.py  models.py  tests.py  views.py
bear@njava:~$ ls -alh
total 20K
drwxr-xr-x 2 bear bear 4.0K 2010-05-19 23:58 .
drwxr-xr-x 3 bear bear 4.0K 2010-05-19 23:58 ..
-rw-r--r-- 1 bear bear    0 2010-05-19 23:58 __init__.py
-rw-r--r-- 1 bear bear   57 2010-05-19 23:58 models.py
-rw-r--r-- 1 bear bear  514 2010-05-19 23:58 tests.py
-rw-r--r-- 1 bear bear   26 2010-05-19 23:58 views.py

编辑models

bear@njava:~/njava/news$vi models.py
from django.db import models

# Create your models here.
class post(models.Model):
      title = models.CharField(max_length = 300)
      desc = models.CharField(max_length = 300)
      content = models.CharField(max_length = 2000)
      tags = models.CharField(max_length = 300)
bear@njava:~/njava/news$cd ..
bear@njava:~/njava$vi settings.py
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'njava.news'
)
bear@njava:~/njava/news$ python manage.py sql news
BEGIN;
CREATE TABLE "news_post" (
    "id" integer NOT NULL PRIMARY KEY,
    "title" varchar(300) NOT NULL,
    "desc" varchar(300) NOT NULL,
    "content" varchar(2000) NOT NULL,
    "tags" varchar(300) NOT NULL
)
;
COMMIT;
bear@njava:~/njava$
bear@njava:~/njava$python manage.py syncdb

Note the following:

1 The exact output will vary depending on the database you are using.
2 Table names are automatically generated by combining the name of the app (polls) and the lowercase name of the model — poll and choice. (You can override this behavior.)
3 Primary keys (IDs) are added automatically. (You can override this, too.)
4 By convention, Django appends “_id” to the foreign key field name. Yes, you can override this, as well.
5 The foreign key relationship is made explicit by a REFERENCES statement.
6 It’s tailored to the database you’re using, so database-specific field types such as auto_increment (MySQL), serial (PostgreSQL), or integer primary key (SQLite) are handled for you automatically. Same goes for quoting of field names — e.g., using double quotes or single quotes. The author of this tutorial runs PostgreSQL, so the example output is in PostgreSQL syntax.
7 The sql command doesn’t actually run the SQL in your database – it just prints it to the screen so that you can see what SQL Django thinks is required. If you wanted to, you could copy and paste this SQL into your database prompt. However, as we will see shortly, Django provides an easier way of committing the SQL to the database.

If you’re interested, also run the following commands:

1 python manage.py validate — Checks for any errors in the construction of your models.
2 python manage.py sqlcustom polls — Outputs any custom SQL statements (such as table modifications or constraints) that are defined for the application.
3 python manage.py sqlclear polls — Outputs the necessary DROP TABLE statements for this app, 4 according to which tables already exist in your database (if any).
5 python manage.py sqlindexes polls — Outputs the CREATE INDEX statements for this app.
6 python manage.py sqlall polls — A combination of all the SQL from the sql, sqlcustom, and sqlindexes commands.

run syncdb again to create those model tables in your database

The syncdb command runs the sql from ‘sqlall’ on your database for all apps in INSTALLED_APPS that don’t already exist in your database. This creates all the tables, initial data and indexes for any apps you have added to your project since the last time you ran syncdb. syncdb can be called as often as you like, and it will only ever create the tables that don’t exist.

使用shell

bear@bear-laptop:~/Sites/django/tt$ python manage.py shell
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from tt.news.models import Post
>>> Post.objects.all()
[]
>>> import datetime
>>> p=Post(title="title test",desc="this is a test desc",tags="a,b,c,e",content="this content")
>>> p.save()
>>> p.id
1L
>>> p.title
'title test'
>>> Post.objects.all()
[
]
>>>

link:http://docs.djangoproject.com/en/dev/intro/tutorial01/#intro-tutorial01

Tags: ,

星期四, 20 5 月, 2010 Web

Leave a Reply

1LMooBmUE153Wnd3zDryWvDyXxQudbFxDr