Django的第一个web程序及深入学习

时间:2023-03-08 21:23:20

本学习历程参照Practical Django Projects和http://djangobook.py3k.cn上翻译的内容进行

注:本例以本机加以说明:

根据Django的安装过程可知:在命令行执行python django-admin.py startproject mysite 则在当前目录下自动创建了一个文件夹mysite,对于本机而言位于

D:\ProgramFile\python2.7.4\Scripts;在该文件夹下包含一个同名的mysite文件夹和manage.py文件,在二级mysite文件夹中包含有4个.py文件:

__init__.py   manage.py   settings.py   urls.py 

接下来在一级mysite文件夹下新建一个.py文件:views.py,其内容如下:
from django.http import HttpResponse

def hello(request):
return HttpResponse("Hello world")

然后修改urls.py的内容,如下:

#from django.conf.urls import patterns, include, url
from django.conf.urls.defaults import *
from views import hello
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover() urlpatterns = patterns('',
('^hello/$', hello),
# 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)),
)

注:上述代码中from views import hello,其中views.py放在了安装目录下,对于本机即为D:\ProgramFile\python2.7.4\views.py

原则就是保证程序执行后能够从系统路径中找到views.py从而import views,要注意!

然后cd到manage.py所在文件夹,在命令行执行python manage.py runserver,之后出现Django的第一个web程序及深入学习

则可以打开浏览器再在地址栏输入http://127.0.0.1:8000/hello/即可打开page显示出:Hello world,至此hello world的web程序成功!

Chapter 3:Customizing the Simple CMS

1.Adding Rich-Text Editing

选用TinyMCE:从官网http://tinymce.moxiecode.com/下载最新的稳定版本,此处我下载的是4.0.4版本

解压之后的路径\tinymce\js\tinymce,在tinymce目录中包含所有的TinyMCE code,对于本机实际路径为

D:\ProgramFile\python2.7.4\tinymce\js\tinymce(根据实际解压后的路径为准)然后打开工程下的urls.py file,将此路径添加进去,如下所示

 from django.conf.urls import patterns, include, url
#from django.conf.urls.defaults import *
#from views import hello
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
from blog.views import * urlpatterns = patterns('',
# ('^hello/$', hello),
# 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)),
url(r'^blog/$', archive),
(r'^tinymace/(?P<path>.*)$', 'django.views.static.serve',
{ 'document_root': 'D:\ProgramFile\python2.7.4\tinymce\js\tinymce' }), (r'', include('django.contrib.flatpages.urls')),
)

urls.py

接着就可以添加合适的JavaScript来调用template以增加和编辑flat pages

The admin application is not only designed to use its own templates as a fallback, but it also lets you provide your own if you’d like to customize it.

默认情况下,admin application将在以下几个地方寻找template:

(1).admin/flatpages/flatpage/change_form.html

(2).admin/flatpages/change_form.html

(3).admin/change_form.html

注:此处的实际路径就是在django目录下django\contrib\admin\templates\admin,与实际情况会有些出入,注意!

2.Right now I want to customize the interface for only one specific model.So inside my templates directory, create an admin subdirectory. Then create a flatpages subdirectory inside admin and a flatpage subdirectory inside flatpages. Finally, copy the change_form template from django/contrib/admin/tem-plates/admin/change_form.html in my copy of Django into the admin/flatpages/flatpage/ directory I just created.

对于本机即为:D:\ProgramFile\python2.7.4\Scripts\html\django-templates\admin\flatpages\flatpage

Then open up the change_form.html in my template directory and add it to add appropriate JavaScript for TinyMCE.

You wil see the following:  {{ media }}

Immediately below that, add the following:

<script type="text/javascript" src="/tinymce/tinymce.js"></script>
<script type="text/javascript">
tinyMCE.init({
mode: "textareas",
theme: "simple"
});
</script>

此处有很多问题需要解决:

首先在官网上有3中TinyMCE package可以下载:TinyMCE 4.0.4 ,TinyMCE 4.0.4 jQuery package,TinyMCE 4.0.4 development package

下载TinyMCE 4.0.4解压后目录为tinymce\js\tinymce里面包含一个tinymce.min.js文件

下载TinyMCE 4.0.4 development package解压后目录同样为tinymce\js\tinymce但里面包含很多js文件:tinymce.min.js,tinymce.js,tinymce.dev.js等,故根据上述change_form.html中添加内容应该是TinyMCE 4.0.4 development package

第二.在setting.py中

TEMPLATE_DIRS = (
'D:/ProgramFile/python2.7.4/Scripts/html/django-templates/admin/flatpages/flatpage',
# 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.
)

所以要将路径中的反斜线\改为顺斜线/

第三.在urls.py中添加patterns:

(r'^tinymce/(?P<path>.*)$', 'django.views.static.serve',
{ 'document_root': 'D:\ProgramFile\python2.7.4\tinymce\js\tinymce' }),

在执行python manage.py runserver后打开浏览器输入http://127.0.0.1:8000/tinymce/提示报错将上述路径中\tinymce的\t当做了制表符,这个该如何解决,难道要改文件名吗?

第四. src="/tinymce/tinymce.js"中的路径要写完整的绝对路径吗?

反复试验始终未能解决??????

注意:我安装的是独立的django,网上还有一种django是打包有tinymce的:如 django-tinymce 1.5.1

问题解决啦:对于上述的第三个路径问题,为避免windows和linux系统路径格式的冲突问题,采用os.path来解决,具体见后面代码

1.首先在D盘创建一个文件夹DjangoProject,作为整个工程的目录,在命令行cd到该目录下,执行

python D:\ProgramFile\python2.7.4\Scripts\django-admin.py startproject cms

(注:此处可将D:\ProgramFile\python2.7.4\Scripts添加到环境变量path中,如此直接执行python django-admin.py startproject cms),于是便在DjangoProject中自动生成一个cms文件夹,其中包括一个同名cms文件夹和manage.py文件(注:此处与老版本django不同),二级cms文件夹中包括4个文件,分别为:__init__.py    settings.py  urls.py  wsgi.py

2.然后将tiny_mce解压后的文件夹放到一级cms中:具体的directory为:D:\DjangoProject\cms\js\tiny_mce\tiny_mce.js

copy the change_form template from django/contrib/admin/tem-plates/admin/change_form.html in your copy of Django into the admin/flatpages/flatpage/ directory you just created.具体为:D:\DjangoProject\templates\cms\admin\flatpages\flatpage\change_form.html

之后更改setting.py和urls.py的内容,详细代码如下:

 # Django settings for cms project.
import os PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
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': os.path.join(PROJECT_ROOT, 'cms.db'), # 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.
}
} # Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.4/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 = 'Asia/Shanghai PRC' # 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: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '' # 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: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = '' # URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
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 = 'j7+nqq-%g=#lq2xm+$l^tpik-%r&amp;@*h@ws#*1cvw&amp;bs5=2vx$e' # 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 = 'cms.urls' # Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'cms.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.
os.path.join(PROJECT_ROOT, '../../templates/cms/'),
) INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.flatpages',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
) # A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}

setting.py

 #from django.conf.urls import patterns, include, url
from django.conf.urls.defaults import * import os
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover() urlpatterns = patterns('',
# Examples:
# url(r'^$', 'cms.views.home', name='home'),
# url(r'^cms/', include('cms.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)), (r'^tiny_mce/(?P<path>.*)$', 'django.views.static.serve',
{ 'document_root': ROOT_PATH + '../js/tiny_mce/' }),
(r'', include('django.contrib.flatpages.urls')),
)

urls.py

注意2、4 line:采用os.path的格式书写绝对路径

urls.py中

(r'^tiny_mce/(?P<path>.*)$', 'django.views.static.serve',
{ 'document_root': ROOT_PATH + '../js/tiny_mce/' }),其中../代表上一级目录,../../代表上一级的上一级目录,/代表当前目录

至此,tinymce的问题解决,打开浏览器可以看到如下的效果:

Django的第一个web程序及深入学习

但是后来重新运行又没有编辑栏,貌似不稳定,不知是何情况???

接下来创建一个app:

Adding a  search  system to the  cms

打开命令行,cd到manage.py所在的目录:执行python manage.py startapp search

则在工程中自动生成search文件夹,文件夹中包括以下文件Django的第一个web程序及深入学习

接着打开视图函数view.py: