django之旅 1.hello world
一但你安装好了python,django和(可选的)数据库及相关库,你就可以通过创建一个project,迈出开发django应用的第一步。
项目 是 Django 实例的一系列设置的集合,它包括数据库配置、Django 特定选项以及应用程序的特定设置。
django采用的是MTV模式,即Models、Temples、Views三层,类似.net的MVC模式
首先创建一个django项目,在上一篇django安装配置中有说明,然后加载进wingide中。
该项目下包含4个文件:
mysite/ mysite/ __init__.py wsgi.py settings.py urls.py manage.py
文件如下:
-
__init__.py :让 Python 把该目录当成一个开发包 (即一组模块)所需的文件。 这是一个空文件,一般你不需要修改它。
-
manage.py :一种命令行工具,允许你以多种方式与该 Django 项目进行交互。 键入python manage.py help,看一下它能做什么。 你应当不需要编辑这个文件;在这个目录下生成它纯是为了方便
-
settings.py :该 Django 项目的设置或配置。 查看并理解这个文件中可用的设置类型及其默认值。
-
urls.py:Django项目的URL设置。 可视其为你的django网站的目录。
尽管这些的文件很小,但这些文件已经构成了一个可运行的Django应用。
创建好这些后就开始配置项目,首先我们开始配置setting.py
# Django settings for eshop project. DEBUG = True TEMPLATE_DEBUG = DEBUG
这个是设置是否编译调试程序
ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': './data.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. } } # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = [] # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'zh-cn' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/var/www/example.com/media/" MEDIA_ROOT = './media' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://example.com/media/", "http://media.example.com/" MEDIA_URL = '/media/' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/var/www/example.com/static/" STATIC_ROOT = './static' # URL prefix for static files. # Example: "http://example.com/static/", "http://static.example.com/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 's(t*k5l+dof0m28bd13%jc%z=6p$p8mjf=#mq9d4*94+7@@l+u' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'eshop.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'eshop.wsgi.application' 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. './templ' )
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',
'order'
)
DATABASES 配置后台使用的数据库,
LANGUAGE_CODE表示语种,
MEDIA_ROOT为媒体文件存放路径,
SECRET_KEY为加密密钥,
ROOT_URLCONF为url.py存放路径,
INSTALLED_APPS 为App目录,
TEMPLATE_DIRS为Temples的目录
配置完setting后,接着配置urls
from django.conf.urls 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'^$', 'order.views.index', name='home'), # url(r'^eshop/', include('eshop.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)), )
这里需要将注销的url(r'^$', 'order.views.index', name='home')还原,这条语句是调用order这个应用中的views.py文件中的index方法,views.py内容如下
# Create your views here. from django.http import HttpResponse #---------------------------------------------------------------------- def index(request): """""" return HttpResponse("hello python")
如果要启用admin的话还需要将下面这三条语句前的注释符号去掉
from django.contrib import admin admin.autodiscover()
url(r'^admin/', include(admin.site.urls))
创建完项目后,还需要创建app ,在进入创建的项目的目录输入“python manage.py startapp order”,order为app名称,即在根目录下会创建一个order文件夹。
该文件夹下面同样包含四个文件
order/
models.py
tests.py
views.py
__init__.py
models,views,__init__文件都为空,这个就是MTV中的M和V
models是创建数据库表
from django.db import models # Create your models here. class Product(models.Model): name = models.CharField("product_name",max_length=30)
views代码已经在上文中贴出。
另外我们还需要在order目录下添加一个admin.py文件,该文件的作用是管理models
from django.contrib import admin from models import Product admin.site.register(Product)
product为model,如果有多个model,则表述方法为from models import <model1,model2>,另外需要将每个model注册一次 amin.site.register(model1)
到这里差不多弄完了,最后一步是生成数据库,进入项目根目录,输入“python manage.py syncdb”命令,然后按照提示输入数据库账号、密码等信息。
最后将manage.py设置为主运行文件,运行时设置Run Arguments为runserver 127.0.0.1:8000,然后我们可以通过浏览器访问“127.0.0.1:8000”进入数据后台管理中心。