如何使用Django快速构建Web应用

来源:互联网 时间:1970-01-01

下载Django

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

安装Django

解压缩下载包

python setup.py install

创建项目【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里非常强大的一个特性

运行开发服务器

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

manage.py runserver

 

创建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'

)

设计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)

 

设置数据库

setting.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.

    }

}

创建表

manage.py syncdb

设置自动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)

 

登录后台

相关阅读:
Top