Python3.7/Mysql5.7/Pycharm/Node/Django3.0
创建Django项目/数据迁移/更换数据库为Mysql
(venv) ➜ django-admin startproject django_vue
(venv) ➜ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying sessions.0001_initial... OK
mysql> CREATE DATABASE django_vue_db CHARACTER SET utf8;
(venv) ➜ pip install mysqlclient
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_vue_db',
'USER': 'root',
'PASSWORD': 'xxxxxxx',
'HOST': '127.0.0.1',
}
}
python manage.py migrate
(venv) ➜ python manage.py startapp api_test
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api_test',
]
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class Book(models.Model):
book_name = models.CharField(max_length=128)
add_time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.book_name
在api_test目录下的views里我们新增两个接口,一个是show_books返回所有的书籍列表(通过JsonResponse返回能被前端识别的json格式数据),二是add_book接受一个get请求,往数据库里添加一条book数据
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.core import serializers
from django.http import JsonResponse
import json
from .models import Book
@require_http_methods(["GET"])
def add_book(request):
response = {}
try:
book = Book(book_name=request.GET.get('book_name'))
book.save()
response['msg'] = 'success'
response['error_num'] = 0
except Exception as e:
response['msg'] = str(e)
response['error_num'] = 1
return JsonResponse(response)
@require_http_methods(["GET"])
def show_books(request):
response = {}
try:
books = Book.objects.filter()
response['list'] = json.loads(serializers.serialize("json", books))
response['msg'] = 'success'
response['error_num'] = 0
except Exception as e:
response['msg'] = str(e)
response['error_num'] = 1
return JsonResponse(response)
from django.conf.urls import url, include
from .views import *
urlpatterns = [
url(r'add_book$', add_book, ),
url(r'show_books$', show_books, ),
]
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView
import api_test.urls
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include(api_test.urls)),
]
python manage.py makemigrations api_test
python manage.py migrate
http://127.0.0.1:8000/api/add_book/?book_name=davieyang
HTTP/1.1 200 OK
Content-Length: 34
Content-Type: application/json
Date: Sun, 15 Dec 2019 09:11:12 GMT
Server: WSGIServer/0.2 CPython/3.7.4
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
{
"error_num": 0,
"msg": "success"
}
http://127.0.0.1:8000/api/add_book/?book_name=测试开发技术
HTTP/1.1 200 OK
Content-Length: 34
Content-Type: application/json
Date: Sun, 15 Dec 2019 09:11:44 GMT
Server: WSGIServer/0.2 CPython/3.7.4
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
{
"error_num": 0,
"msg": "success"
}
调用接口,显示Django App中所有书名列表
http://127.0.0.1:8000/api/show_books
HTTP/1.1 200 OK
Content-Length: 305
Content-Type: application/json
Date: Sun, 15 Dec 2019 09:13:48 GMT
Server: WSGIServer/0.2 CPython/3.7.4
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
{
"error_num": 0,
"list": [
{
"fields": {
"add_time": "2019-12-15T09:11:12.673Z",
"book_name": "mikezhou_talk"
},
"model": "api_test.book",
"pk": 1
},
{
"fields": {
"add_time": "2019-12-15T09:11:44.305Z",
"book_name": "测试开发技术"
},
"model": "api_test.book",
"pk": 2
}
],
"msg": "success"
}
npm install -g cnpm --registry=https://registry.npm.taobao.org
cnpm install -g vue-cli
vue-init webpack frontend
cd frontend
cnpm install
cnpm install vue-resource
cnpm install element-ui
Home.vue文件代码:
新增
{{ scope.row.pk }}
{{ scope.row.fields.book_name }}
{{ scope.row.fields.add_time }}
```js
import Vue from 'vue'
import Router from 'vue-router'
// import HelloWorld from '@/components/HelloWorld'
import Home from '@/components/Home'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
}
]
})
```js
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import VueResource from 'vue-resource'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
Vue.use(VueResource)
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: ' '
})
pip install django-cors-headers
```python..注意中间件的添加顺序
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
在前端工程frontend目录下,输入npm run dev启动node自带的服务器,浏览器会自动打开, 我们能看到页面:
尝试新增书籍,如填入:“自动化测试实战宝典”,新增的书籍信息会实时反映到页面的列表中,这得益于Vue.js的数据双向绑定特性
在前端工程frontend目录下,输入npm run build,如果项目没有错误的话,就能够看到所有的组件、css、图片等都被webpack自动打包到dist目录下了:
整合Django和Vue.js前端
目前已经分别完成了Django后端和Vue.js前端工程的创建和编写,但实际上它们是运行在各自的服务器上,和我们的要求是不一致的。因此我们须要把Django的TemplateView指向我们刚才生成的前端dist文件即可
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include(api_test.urls)),
url(r'^$', TemplateView.as_view(template_name="index.html")),
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS':['frontend/dist'],
'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',
],
},
},
]
# Add for vuejs
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "frontend/dist/static"),
]
下载安装node.js, 官方下载地址https://nodejs.org/en/,下载符合自己操作系统版本的即可,安装也是傻瓜式安装。
安装完成后,在命令行输入node,如下展示则表示成功
C:\Users\Administrator>node -v
v8.17.0
在命令行输入: npm install -g cnpm --registry=https://registry.npm.taobao.org (https://registry.npm.taobao.org/)
之后cnpm install -g vue-cli命令行展示如下内容,则表示成功
C:\Users\Administrator>npm install -g cnpm --registry=https://registry.npm.taobao.org
C:\Users\Administrator\AppData\Roaming\npm\cnpm -> C:\Users\Administrator\AppData\Roaming\npm\node_modules\cnpm\bin\cnpm
+ [email protected]
added 681 packages from 938 contributors in 30.737s
C:\Users\Administrator>cnpm install -g vue-cli
Downloading vue-cli to C:\Users\Administrator\AppData\Roaming\npm\node_modules\vue-cli_tmp
Copying C:\Users\Administrator\AppData\Roaming\npm\node_modules\vue-cli_tmp\[email protected]@vue-cli to C:\Users\Administrator\AppData\Roaming\npm\node_modules\vue-cli
Installing vue-cli's dependencies to C:\Users\Administrator\AppData\Roaming\npm\node_modules\vue-cli/node_modules
[1/20] commander@^2.9.0 installed at node_modules\[email protected]@commander
[2/20] minimatch@^3.0.0 installed at node_modules\[email protected]@minimatch
[3/20] multimatch@^2.1.0 installed at node_modules\[email protected]@multimatch
[4/20] ora@^1.3.0 installed at node_modules\[email protected]@ora
[5/20] rimraf@^2.5.0 existed at node_modules\[email protected]@rimraf
[6/20] consolidate@^0.14.0 installed at node_modules\[email protected]@consolidate
[7/20] chalk@^2.1.0 installed at node_modules\[email protected]@chalk
[8/20] semver@^5.1.0 installed at node_modules\[email protected]@semver
[9/20] [email protected] installed at node_modules\[email protected]@uid
[10/20] read-metadata@^1.0.0 installed at node_modules\[email protected]@read-metadata
[11/20] user-home@^2.0.0 installed at node_modules\[email protected]@user-home
[12/20] tildify@^1.2.0 installed at node_modules\[email protected]@tildify
[13/20] [email protected] existed at node_modules\[email protected]@coffee-script
[14/20] handlebars@^4.0.5 installed at node_modules\[email protected]@handlebars
[15/20] validate-npm-package-name@^3.0.0 installed at node_modules\[email protected]@validate-npm-package-name
[16/20] metalsmith@^2.1.0 installed at node_modules\[email protected]@metalsmith
[17/20] download-git-repo@^1.0.1 installed at node_modules\[email protected]@download-git-repo
[18/20] request@^2.67.0 installed at node_modules\[email protected]@request
[19/20] async@^2.4.0 installed at node_modules\[email protected]@async
[20/20] inquirer@^6.0.0 installed at node_modules\[email protected]@inquirer
deprecate [email protected] › [email protected] › coffee-script@^1.12.4 CoffeeScript on NPM has moved to "coffeescript" (no hyphen)
Recently updated (since 2019-12-30): 3 packages (detail see file C:\Users\Administrator\AppData\Roaming\npm\node_modules\vue-cli\node_modules\.recently_updates.txt)
Today:
→ [email protected] › mime-types@~2.1.19(2.1.26) (11:47:55)
→ [email protected] › [email protected] › [email protected] › [email protected] › [email protected] › readable-stream@^2.3.0(2.3.7) (01:13:39)
→ [email protected] › [email protected] › [email protected](1.43.0) (11:24:37)
All packages installed (239 packages installed from npm registry, used 7s(network 7s), speed 703.07kB/s, json 223(445.45kB), tarball 4.55MB)
[[email protected]] link C:\Users\Administrator\AppData\Roaming\npm\vue@ -> C:\Users\Administrator\AppData\Roaming\npm\node_modules\vue-cli\bin\vue
[[email protected]] link C:\Users\Administrator\AppData\Roaming\npm\vue-init@ -> C:\Users\Administrator\AppData\Roaming\npm\node_modules\vue-cli\bin\vue-init
[[email protected]] link C:\Users\Administrator\AppData\Roaming\npm\vue-list@ -> C:\Users\Administrator\AppData\Roaming\npm\node_modules\vue-cli\bin\vue-list
安装完成后,在命令行输入vue,如下所示,则表示成功
C:\Users\Administrator>vue
Usage: vue [options]
Options:
-V, --version output the version number
-h, --help output usage information
Commands:
init generate a new project from a template
list list available official templates
build prototype a new project
create (for v3 warning only)
help [cmd] display help for [cmd]
deprecate [email protected] › [email protected] › [email protected] › core-js@^2.4.0 core-js@❤️ is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
(venv) D:\PythonPrograms\DjangoPrograms\DjangoVue\frontend>cnpm install element-ui
√ Installed 1 packages
√ Linked 10 latest versions
[1/1] scripts.postinstall [email protected] › [email protected] › [email protected] › core-js@^2.4.0 run "node -e \"try{require('./postinstall')}c
atch(e){}\"", root: "D:\\PythonPrograms\\DjangoPrograms\\DjangoVue\\frontend\\node_modules\\[email protected]@core-js"
Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!
The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock
Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)
[1/1] scripts.postinstall [email protected] › [email protected] › [email protected] › core-js@^2.4.0 finished in 240ms
√ Run 1 scripts
deprecate [email protected] › [email protected] › [email protected] › core-js@^2.4.0 core-js@<3 is no longer maintained and not recommended for us
age due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
√ All packages installed (11 packages installed from npm registry, used 4s(network 4s), speed 23.04kB/s, json 11(87.37kB), tarball 0B)
在命令行输入
C:\Users\Administrator>cnpm install core-js@3
√ Installed 1 packages
√ Linked 0 latest versions
[1/1] scripts.postinstall core-js@3 run "node -e \"try{require('./postinstall')}catch(e){}\"", root: "C:\\Users\\Administrator\\node_modules\\[email protected]@core-js"
[1/1] scripts.postinstall core-js@3 finished in 223ms
√ Run 1 scripts
√ All packages installed (1 packages installed from npm registry, used 2s(network 2s), speed 113.85kB/s, json 1(14.02kB), tarball 158.92kB)
再次执行命令:
(venv) D:\PythonPrograms\DjangoPrograms\DjangoVue\frontend>cnpm install element-ui
√ Installed 1 packages
√ Linked 0 latest versions
√ Run 0 scripts
√ All packages installed (used 539ms(network 536ms), speed 36.7kB/s, json 1(19.67kB), tarball 0B)
deprecate [email protected] › [email protected] › coffee-script@^1.12.4 CoffeeScript on NPM has moved to “coffeescript” (no hyphen)
执行如下命令解决:
C:\Users\Administrator>cnpm install coffeescript
√ Installed 1 packages
√ Linked 0 latest versions
√ Run 0 scripts
Recently updated (since 2019-12-30): 1 packages (detail see file C:\Users\Administrator\node_modules\.recently_updates.txt)
√ All packages installed (1 packages installed from npm registry, used 1s(network 1s), speed 343.98kB/s, json 1(5.39kB), tarball 361.29kB)