Python3 + Django 2.0.4
创建一个项目和一个 APP
- 创建一个叫 HttpTestProject 项目:
django-admin.py startproject HttpTestProject
- 进入项目目录,创建一个叫 HttpTest 的 APP:
python3 manage.py startapp HttpTest
- 进入 APP 目录,创建 static & templates 目录
root@server_1:/var/HttpTestProject# tree
.
├── HttpTest
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ ├── __init__.py
│ │ └── __pycache__
│ │ └── __init__.cpython-35.pyc
│ ├── models.py //数据库相关操作
│ ├── __pycache__
│ │ ├── admin.cpython-35.pyc
│ │ ├── __init__.cpython-35.pyc
│ │ ├── models.cpython-35.pyc
│ │ └── views.cpython-35.pyc
│ ├── static //存放静态文件
│ ├── templates //存放模板文件
│ ├── tests.py
│ └── views.py //请求应答相关操作
├── HttpTestProject
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-35.pyc
│ │ ├── settings.cpython-35.pyc
│ │ ├── urls.cpython-35.pyc
│ │ └── wsgi.cpython-35.pyc
│ ├── settings.py // 本项目及所属 APP 相关配置
│ ├── settings.py.original
│ ├── urls.py //本项目及所属 APP 相关 URL 配置
│ └── wsgi.py //WSGI相关配置
├── manage.py
└── __pycache__
└── manage.cpython-35.pyc
- 将 APP 添加到 项目的 settings.py 文件文件中:
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'HttpTest',
]
- 在 settings.py 中配置允许访问的 host,即请求中的 host 部分:
ALLOWED_HOSTS = ['172.16.2.16',]
简单的请求与应答
- APP 中的 views.py
# coding: utf-8
from django.shortcuts import render
def index(request):
return render(request, 'index.html') //上传index.html文件到templates目录下
- Project 下的urls.py
from django.contrib import admin
from django.urls import path
from HttpTest import views // from my_app import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index'), //path('', views.home, name='home')
]
- 启动 django 监听 8000 端口,访问 http://172.16.2.16:8000,查看 log
root@server_1:/var/HttpTestProject# python3 manage.py runserver 0.0.0.0:8000
Performing system checks...
System check identified no issues (0 silenced).
April 16, 2018 - 06:03:46
Django version 2.0.4, using settings 'HttpTestProject.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
[16/Apr/2018 06:03:49] "GET / HTTP/1.1" 200 231 //访问成功
Django 的一些常用命令
命令 | 含义 |
---|---|
django-admin.py -- version |
查看版本号 |
django-admin.py startproject project_name |
创建项目 |
python3 manage.py startapp app_name |
创建APP |
python3 manage.py makemigrations |
|
python3 manage.py migrate |
|
python3 manage.py runserver 0.0.0.0:8000 |
启用django服务器 |
python3 manage.py flush |
清空数据库 |
python3 manage.py createsuperuser |
创建超级用户 |
python3 manage.py changepassword username |
更改密码 |
python3 manage.py dumpdata appname > appname.json python3 manage.py loaddata appname.json
|
导入数据库 |
python3 manage.py shell |
终端 |
python3 manage.py dbshell |
DB终端 |