DJango - 项目创建

方焱
2023-12-01

项目创建

需要选定一个目录作为项目的主目录
一个项目中可以拥有多个 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

[root@nova-test-uxnpv ~]# mkdir /apps/dat/web/ -p
[root@nova-test-uxnpv ~]# cd /apps/dat/web/
[root@nova-test-uxnpv web]# django-admin startproject demo

目录结构介绍

[root@nova-test-uxnpv 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',
            ],
        },
    },
]
 类似资料: