天天看點

DJango - 項目建立項目建立指令幫助Example

項目建立

需要標明一個目錄作為項目的主目錄

一個項目中可以擁有多個 apps

指令幫助

建立項目方法

django-admin help startproject
usage: django-admin startproject [-h] [--version] [-v {0,1,2,3}]
                                 [--settings SETTINGS]
                                 [--pythonpath PYTHONPATH] [--traceback]
                                 [--no-color] [--template TEMPLATE]
                                 [--extension EXTENSIONS] [--name FILES]
                                 name [directory]

Creates a Django project directory structure for the given project name in the current directory or optionally in the given directory.

positional arguments:
  name                  Name of the application or project.
  directory             Optional destination directory

optional arguments:
  -h, --help            show this help message and exit
  --version             show program's version number and exit
  -v {0,1,2,3}, --verbosity {0,1,2,3}
                        Verbosity level; 0=minimal output, 1=normal output,
                        2=verbose output, 3=very verbose output
  --settings SETTINGS   The Python path to a settings module, e.g.
                        "myproject.settings.main". If this isn't provided, the
                        DJANGO_SETTINGS_MODULE environment variable will be
                        used.
  --pythonpath PYTHONPATH
                        A directory to add to the Python path, e.g.
                        "/home/djangoprojects/myproject".
  --traceback           Raise on CommandError exceptions
  --no-color            Don't colorize the command output.
  --template TEMPLATE   The path or URL to load the template from.
  --extension EXTENSIONS, -e EXTENSIONS
                        The file extension(s) to render (default: "py").
                        Separate multiple extensions with commas, or use -e
                        multiple times.
  --name FILES, -n FILES
                        The file name(s) to render. Separate multiple
                        extensions with commas, or use -n multiple times.
           

建立 apps 方法

django-admin help startapp
usage: django-admin startapp [-h] [--version] [-v {0,1,2,3}]
                             [--settings SETTINGS] [--pythonpath PYTHONPATH]
                             [--traceback] [--no-color] [--template TEMPLATE]
                             [--extension EXTENSIONS] [--name FILES]
                             name [directory]

Creates a Django app directory structure for the given app name in the current directory or optionally in the given directory.

positional arguments:
  name                  Name of the application or project.
  directory             Optional destination directory

optional arguments:
  -h, --help            show this help message and exit
  --version             show program's version number and exit
  -v {0,1,2,3}, --verbosity {0,1,2,3}
                        Verbosity level; 0=minimal output, 1=normal output,
                        2=verbose output, 3=very verbose output
  --settings SETTINGS   The Python path to a settings module, e.g.
                        "myproject.settings.main". If this isn't provided, the
                        DJANGO_SETTINGS_MODULE environment variable will be
                        used.
  --pythonpath PYTHONPATH
                        A directory to add to the Python path, e.g.
                        "/home/djangoprojects/myproject".
  --traceback           Raise on CommandError exceptions
  --no-color            Don't colorize the command output.
  --template TEMPLATE   The path or URL to load the template from.
  --extension EXTENSIONS, -e EXTENSIONS
                        The file extension(s) to render (default: "py").
                        Separate multiple extensions with commas, or use -e
                        multiple times.
  --name FILES, -n FILES
                        The file name(s) to render. Separate multiple
                        extensions with commas, or use -n multiple times.
           

Example

建立項目

項目名稱: demo

[[email protected] ~]# mkdir /apps/dat/web/ -p
[[email protected] ~]# cd /apps/dat/web/
[[email protected] web]# django-admin startproject demo
           

目錄結構介紹

[[email protected] web]# tree .
.
└── demo
    ├── demo
    │   ├── __init__.py
    │   ├── settings.py                    <- 項目配置檔案
    │   ├── urls.py                        <-  URL 路由檔案
    │   └── wsgi.py                        <- 網絡通訊接口
    └── manage.py                          <- django 主管理程式
           

allow host 設定

修改 settings.py 檔案, 可以選擇輸入目前用于監聽 IP 或者直接寫 “*”

ALLOWED_HOSTS = ["*"]
           

假如沒有上述設定, 則啟動項目後會出現下面錯誤

DisallowedHost at /

Invalid HTTP_HOST header: 'x.x.x.x'. You may need to add u'x.x.x.x to ALLOWED_HOSTS.

Request Method: 	GET
Request URL: 	http://x.x.x.x/
Django Version: 	1.11.16
Exception Type: 	DisallowedHost
Exception Value: 	

Invalid HTTP_HOST header: 'x.x.x.x'. You may need to add u'x.x.x.x' to ALLOWED_HOSTS.

Exception Location: 	/usr/lib64/python2.7/site-packages/django/http/request.py in get_host, line 113
           

測試項目啟動

可以用下面方法可以啟動項目用于測試

cd demo
python manage.py runserver 0.0.0.0:80
           

可以看見有下面輸出

Performing system checks...

System check identified no issues (0 silenced).

You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.  (這裡是跟資料庫配置及同步相關,暫時不需要去解決他)
Run 'python manage.py migrate' to apply them.

October 22, 2018 - 02:47:52
Django version 1.11.16, using settings 'demo.settings'
Starting development server at http://0.0.0.0:80/
Quit the server with CONTROL-C.

           

利用 firefox 可以直接進行通路

http://x.x.x.x/
           

網頁上可以看到下面字型

It worked!
Congratulations on your first Django-powered page.

Next, start your first app by running python manage.py startapp [app_label].

You're seeing this message because you have DEBUG = True in your Django settings file and you haven't configured any URLs. Get to work!
           

項目 apps

習慣上, 一個項目可以有多個 apps

我們的代碼都會存放到 apps 目錄下并以 py 檔案結尾

建立一個apps

apps 命名:tiweb

python manage.py startapp tiweb
           

目錄結構

tiweb 目錄下會生成很多 py 檔案, 但目前我們暫時将不會用到這些 py 檔案

├── db.sqlite3                         <- 廢棄,sqlite 資料庫檔案(我們将會采用 Mariadb 作為預設資料庫,後面介紹)
├── demo
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
└── tiweb
    ├── admin.py
    ├── apps.py
    ├── __init__.py
    ├── migrations                     <- 資料庫處理記錄相關資訊你的目錄
    │   └── __init__.py
    ├── models.py                      <-  用于定義資料庫表結構的 python 檔案(以後介紹)
    ├── tests.py
    └── views.py                       <- 習慣上, DJango 會用這個檔案作為入口檔案(url映射到相應的業務處理邏輯)
           

配置 apps

建立 apps 後, 需要對 settings.py 進行修改, 添加新的 apps 定義

vim demo/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'tiweb',                                  <- 新增新的 apps 命名
]
           

setttings.py 設定

  1. apps 設定
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'tiweb',                                  <- 新增新的 apps 命名
]
           
  1. allow host 設定(用于允許主機監聽那些 IP 位址)
ALLOWED_HOSTS = ["*"]
           
  1. 中文支援
LANGUAGE_CODE = 'zh-Hans' 
           
  1. 中國時區支援
TIME_ZONE = 'Asia/Shanghai' 
           
  1. debug 支援
DEBUG = True
           
  1. 靜态檔案位置定義 (習慣上我們會把 js , css, images[jpg, png, gif] 等檔案作為靜态檔案處理)

    目前以 /apps/dat/web/demo/static/ 目錄作為靜态檔案根目錄

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    '/static/',
]
           
  1. MySQL / MariaDB 資料庫連接配接方法
DATABASES = {
        'default' : {
                'ENGINE': 'django.db.backends.mysql',
                'NAME': 'dbname',
                'USER': 'username',
                'PASSWORD': 'password,
                'HOST': 'mysqlIPADDR',
                'PORT': '3306',
        }
}
           
  1. Template 定義

    Template 用于存放一種動态加載資料的模闆網頁應用

    目前以 /apps/dat/web/demo/template/目錄存放 template file

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'template')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]