使用Django如无到有11步快速构建Web应用

1.        下载Django

https://www.djangoproject.com/download/

2.        安装Django

解压缩下载包

python setup.py install

前提是python已安装

3.        创建项目[Project]   (Django-admin.py)

Linux默认安装路径: /usr/bin

windows默认安装路径: C:\PythonXX\Scripts

Django-admin.py startproject mysite

cd mysite,里面有4个文件

__init__.py把这个项目目录变成一个python(package)

manage.py,同这个项目一起工作的工具,最重要的文件

setting.py,项目的设置,包括DB信息、调试标志及其他一些重要的变量

urls.py文件在Django里叫URLconf,将URL模式映射到你应用程序上的配置文件。URLconfDjango里非常强大的一个特性

4.        运行开发服务器

Django内置了web服务器,可以用做开发,改代码后不需要重启服务器,提高开发效率

manage.py runserver

clip_image002

 

5.        创建Web应用[App]

manage.py startapp MessageBoard

project一样,app也是一个包,打开setting.py,找到INSTALLED_APPS元组,把app以模块形式添加到元组中

INSTALLED_APPS = (

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.sites',

    'django.contrib.messages',

    'django.contrib.staticfiles',

    'mysite.MessageBoard'

)

6.        设计Model

from django.db import models

 

# Create your models here.

class Message(models.Model):

    title = models.CharField(max_length=100)

    body = models.TextField()

    user = models.CharField(max_length=100)

 

7.        设置数据库

settings.py

DATABASES = {

    'default': {

        'ENGINE': 'mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.

        'NAME': 'messageboard',                      # Or path to database file if using sqlite3.

        'USER': 'root',                      # Not used with sqlite3.

        'PASSWORD': '123456',                  # Not used with sqlite3.

        'HOST': 'localhost',                      # Set to empty string for localhost. Not used with sqlite3.

        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.

    }

}

8.        创建表

manage.py syncdb

9.        设置自动admin应用

settings.pyINSTALLED_APPS元组里的’django.contrib.auth’下面添加

‘django.contrib.admin’,

 urls.py中添加以下代码

from django.conf.urls.defaults import patterns, include, url

 

# Uncomment the next two lines to enable the admin:

from django.contrib import admin

admin.autodiscover()

 

urlpatterns = patterns('',

    # Examples:

    # url(r'^$', 'mysite.views.home', name='home'),

    # url(r'^mysite/', include('mysite.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)),

)

models.py里增加两行代码

from django.db import models

from django.contrib import admin

 

# Create your models here.

class Message(models.Model):

    title = models.CharField(max_length=100)

    body = models.TextField()

    user = models.CharField(max_length=100)

 

admin.site.register(Message)

 

10.   登录后台

clip_image004

点开MessageboardAdd新增Message对象,然后点开的Messages列表。

clip_image006

如图Messages列表上显示的不是各个字段,而是默认显示Message object,需要再次点开才能查看对象属性。

models.py增加这么几行代码:

class Message(models.Model):

    title = models.CharField(max_length=100)

    body = models.TextField()

    user = models.CharField(max_length=100)

 

class MessageAdmin(admin.ModelAdmin):

    list_display = ("title", "user")

 

admin.site.register(Message, MessageAdmin)

 

可以看到列表变成

clip_image008

 

11.   创建前台页面

创建模板

MessageBoard文件夹下新建templates文件夹,在此文件夹下新建MessageBoard.htm文件

{% for message in messages %}

<h2>{{message.title}}</h2>

<p>{{message.body}}</p>

<p>{{message.user}}</p>

{% endfor %}

 

创建视图函数

回到MessageBoard文件夹,在views.py文件中输入

# Create your views here.

from django.template import loader, Context

from django.http import HttpResponse

from mysite.MessageBoard.models import Message

 

def MessageBoardView(request):

    messages = Message.objects.all()

    t = loader.get_template("MessageBoard.htm")

    c = Context({"messages": messages})

    return HttpResponse(t.render(c))

 

创建Url模式

mysite/urls.py中加入

url(r'^MessageBoard/$', include('mysite.MessageBoard.urls')),

mysite/MessageBoard/下新建urls.py,加入:

from django.conf.urls.defaults import *

from mysite.MessageBoard.views import MessageBoardView

 

urlpatterns = patterns('',

    url(r'^$', MessageBoardView),

)

母版页

mysite/MessageBoard/templates文件夹下新建母版页文件Master.htm

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <style type="text/css">

        body

        {

            color: Olive;

            background-color: black;

        }

        h2

        {

            border-top: 1px solid white;

        }

    </style>

</head>

<body>

    <h1>

        Message Board</h1>

    {% block content %} {% endblock %}

</body>

</html>

 

其中{% block NAME %} {% endblock %}为占位符,NAME为自定义的占位符名称

修改MessageBoard.htm文件,加上对Master.htm的引用

{% extends "Master.htm" %}

{% block content %}

{% for message in messages %}

<h2>

    {{message.title}}</h2>

<p>

    {{message.body}}</p>

<p>

    {{message.user}}</p>

{% endfor %}

{%endblock%}

 

查看效果

clip_image010

 

 

posted on 2011-08-28 22:35  yaksea  阅读(1507)  评论(0编辑  收藏  举报