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


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

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

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

    D:ProgramFilepython2.7.4Scripts;在该文件夹下包含一个同名的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:ProgramFilepython2.7.4views.py

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

    然后cd到manage.py所在文件夹,在命令行执行python manage.py runserver,之后出现

    则可以打开浏览器再在地址栏输入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版本

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

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

     1 from django.conf.urls import patterns, include, url
     2 #from django.conf.urls.defaults import *
     3 #from views import hello
     4 # Uncomment the next two lines to enable the admin:
     5 from django.contrib import admin
     6 admin.autodiscover()
     7 from blog.views import *
     8 
     9 urlpatterns = patterns('',
    10 #    ('^hello/$', hello),
    11     # Examples:
    12     # url(r'^$', 'mysite.views.home', name='home'),
    13     # url(r'^mysite/', include('mysite.foo.urls')),
    14 
    15     # Uncomment the admin/doc line below to enable admin documentation:
    16     # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    17 
    18     # Uncomment the next line to enable the admin:
    19      url(r'^admin/', include(admin.site.urls)),
    20      url(r'^blog/$', archive),
    21     (r'^tinymace/(?P<path>.*)$', 'django.views.static.serve',
    22                        { 'document_root': 'D:ProgramFilepython2.7.4	inymcejs	inymce' }),
    23       
    24     (r'', include('django.contrib.flatpages.urls')),
    25 )
    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目录下djangocontribadmin emplatesadmin,与实际情况会有些出入,注意!

     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:ProgramFilepython2.7.4Scriptshtmldjango-templatesadminflatpagesflatpage

     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解压后目录为tinymcejs inymce里面包含一个tinymce.min.js文件

    下载TinyMCE 4.0.4 development package解压后目录同样为tinymcejs inymce但里面包含很多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:ProgramFilepython2.7.4 inymcejs inymce' }),

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

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

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

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

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

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

    python D:ProgramFilepython2.7.4Scriptsdjango-admin.py startproject cms

    (注:此处可将D:ProgramFilepython2.7.4Scripts添加到环境变量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:DjangoProjectcmsjs iny_mce iny_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 emplatescmsadminflatpagesflatpagechange_form.html

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

      1 # Django settings for cms project.
      2 import os
      3 
      4 PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
      5 DEBUG = True
      6 TEMPLATE_DEBUG = DEBUG
      7 
      8 ADMINS = (
      9     # ('Your Name', 'your_email@example.com'),
     10 )
     11 
     12 MANAGERS = ADMINS
     13 
     14 DATABASES = {
     15     'default': {
     16         'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
     17         'NAME': os.path.join(PROJECT_ROOT, 'cms.db'),                      # Or path to database file if using sqlite3.
     18         'USER': '',                      # Not used with sqlite3.
     19         'PASSWORD': '',                  # Not used with sqlite3.
     20         'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
     21         'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
     22     }
     23 }
     24 
     25 # Hosts/domain names that are valid for this site; required if DEBUG is False
     26 # See https://docs.djangoproject.com/en/1.4/ref/settings/#allowed-hosts
     27 ALLOWED_HOSTS = []
     28 
     29 # Local time zone for this installation. Choices can be found here:
     30 # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
     31 # although not all choices may be available on all operating systems.
     32 # In a Windows environment this must be set to your system time zone.
     33 TIME_ZONE = 'Asia/Shanghai PRC'
     34 
     35 # Language code for this installation. All choices can be found here:
     36 # http://www.i18nguy.com/unicode/language-identifiers.html
     37 LANGUAGE_CODE = 'zh-CN'
     38 
     39 SITE_ID = 1
     40 
     41 # If you set this to False, Django will make some optimizations so as not
     42 # to load the internationalization machinery.
     43 USE_I18N = True
     44 
     45 # If you set this to False, Django will not format dates, numbers and
     46 # calendars according to the current locale.
     47 USE_L10N = True
     48 
     49 # If you set this to False, Django will not use timezone-aware datetimes.
     50 USE_TZ = True
     51 
     52 # Absolute filesystem path to the directory that will hold user-uploaded files.
     53 # Example: "/home/media/media.lawrence.com/media/"
     54 MEDIA_ROOT = ''
     55 
     56 # URL that handles the media served from MEDIA_ROOT. Make sure to use a
     57 # trailing slash.
     58 # Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
     59 MEDIA_URL = ''
     60 
     61 # Absolute path to the directory static files should be collected to.
     62 # Don't put anything in this directory yourself; store your static files
     63 # in apps' "static/" subdirectories and in STATICFILES_DIRS.
     64 # Example: "/home/media/media.lawrence.com/static/"
     65 STATIC_ROOT = ''
     66 
     67 # URL prefix for static files.
     68 # Example: "http://media.lawrence.com/static/"
     69 STATIC_URL = '/static/'
     70 
     71 # Additional locations of static files
     72 STATICFILES_DIRS = (
     73     # Put strings here, like "/home/html/static" or "C:/www/django/static".
     74     # Always use forward slashes, even on Windows.
     75     # Don't forget to use absolute paths, not relative paths.
     76 )
     77 
     78 # List of finder classes that know how to find static files in
     79 # various locations.
     80 STATICFILES_FINDERS = (
     81     'django.contrib.staticfiles.finders.FileSystemFinder',
     82     'django.contrib.staticfiles.finders.AppDirectoriesFinder',
     83 #    'django.contrib.staticfiles.finders.DefaultStorageFinder',
     84 )
     85 
     86 # Make this unique, and don't share it with anybody.
     87 SECRET_KEY = 'j7+nqq-%g=#lq2xm+$l^tpik-%r&amp;@*h@ws#*1cvw&amp;bs5=2vx$e'
     88 
     89 # List of callables that know how to import templates from various sources.
     90 TEMPLATE_LOADERS = (
     91     'django.template.loaders.filesystem.Loader',
     92     'django.template.loaders.app_directories.Loader',
     93 #     'django.template.loaders.eggs.Loader',
     94 )
     95 
     96 MIDDLEWARE_CLASSES = (
     97     'django.middleware.common.CommonMiddleware',
     98     'django.contrib.sessions.middleware.SessionMiddleware',
     99     'django.middleware.csrf.CsrfViewMiddleware',
    100     'django.contrib.auth.middleware.AuthenticationMiddleware',
    101     'django.contrib.messages.middleware.MessageMiddleware',
    102     # Uncomment the next line for simple clickjacking protection:
    103     # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
    104 )
    105 
    106 ROOT_URLCONF = 'cms.urls'
    107 
    108 # Python dotted path to the WSGI application used by Django's runserver.
    109 WSGI_APPLICATION = 'cms.wsgi.application'
    110 
    111 TEMPLATE_DIRS = (
    112     # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    113     # Always use forward slashes, even on Windows.
    114     # Don't forget to use absolute paths, not relative paths.
    115     os.path.join(PROJECT_ROOT, '../../templates/cms/'),
    116 )
    117 
    118 INSTALLED_APPS = (
    119     'django.contrib.auth',
    120     'django.contrib.contenttypes',
    121     'django.contrib.sessions',
    122     'django.contrib.sites',
    123     'django.contrib.messages',
    124     'django.contrib.staticfiles',
    125     'django.contrib.admin',
    126     'django.contrib.flatpages',
    127     # Uncomment the next line to enable the admin:
    128     # 'django.contrib.admin',
    129     # Uncomment the next line to enable admin documentation:
    130     # 'django.contrib.admindocs',
    131 )
    132 
    133 # A sample logging configuration. The only tangible logging
    134 # performed by this configuration is to send an email to
    135 # the site admins on every HTTP 500 error when DEBUG=False.
    136 # See http://docs.djangoproject.com/en/dev/topics/logging for
    137 # more details on how to customize your logging configuration.
    138 LOGGING = {
    139     'version': 1,
    140     'disable_existing_loggers': False,
    141     'filters': {
    142         'require_debug_false': {
    143             '()': 'django.utils.log.RequireDebugFalse'
    144         }
    145     },
    146     'handlers': {
    147         'mail_admins': {
    148             'level': 'ERROR',
    149             'filters': ['require_debug_false'],
    150             'class': 'django.utils.log.AdminEmailHandler'
    151         }
    152     },
    153     'loggers': {
    154         'django.request': {
    155             'handlers': ['mail_admins'],
    156             'level': 'ERROR',
    157             'propagate': True,
    158         },
    159     }
    160 }
    setting.py
     1 #from django.conf.urls import patterns, include, url
     2 from django.conf.urls.defaults import *
     3 
     4 import os
     5 ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
     6 # Uncomment the next two lines to enable the admin:
     7 from django.contrib import admin
     8 admin.autodiscover()
     9 
    10 urlpatterns = patterns('',
    11     # Examples:
    12     # url(r'^$', 'cms.views.home', name='home'),
    13     # url(r'^cms/', include('cms.foo.urls')),
    14 
    15     # Uncomment the admin/doc line below to enable admin documentation:
    16     # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    17 
    18     # Uncomment the next line to enable the admin:
    19     url(r'^admin/', include(admin.site.urls)),
    20 
    21     (r'^tiny_mce/(?P<path>.*)$', 'django.views.static.serve', 
    22         { 'document_root': ROOT_PATH + '../js/tiny_mce/' }),
    23     (r'', include('django.contrib.flatpages.urls')),
    24 )
    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的问题解决,打开浏览器可以看到如下的效果:

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

    接下来创建一个app:

     Adding a  search  system to the  cms

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

    则在工程中自动生成search文件夹,文件夹中包括以下文件

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

  • 相关阅读:
    Mysql数据库相关流程图/原理图
    【nginx】配置Nginx实现负载均衡
    数据库设计——评论回复功能
    html生成pdf
    cmd下载echarts包
    windows安装cnpm步骤
    你不在,是一年一年,你在,是春夏秋冬
    聚合
    Beyond compare4密钥
    ExtJs目录说明
  • 原文地址:https://www.cnblogs.com/CoolRandy/p/3276472.html
Copyright © 2020-2023  润新知